on Jun 26th, 2008Stored Procedures in MySQL

The programmers and developers all over the world are celebrating the existence of MySQL 5.0 for a good reason. The version has finally paved the way for using stored procedures with this popular open source database. The stored procedures are hoarded at database server in the form of commands and SQL statements and could be invoked for any type of application. Thus, there is advantage for programmers to shed away the need of creating their own SQL; a tiresome job.

Without taking much of the time, let us understand the syntax for utilizing the procedures:

  1.  
  2. CREATE ProcedureCREATE    [DEFINER = { user | CURRENT_USER }]PROCEDURE sp_name ([proc_parameter[,…]])
  3.  
  4. [characteristic …] routine_body
  5.  
  6. IN the above syntax, the parameters are specified AS IN, OUT OR INOUT. However, IN case of CREATE FUNCTION displayed below, the only parameter allowed IS IN.
  7.  
  8. CREATE
  9.  
  10. [DEFINER = { user | CURRENT_USER }]
  11.  
  12. FUNCTION sp_name ([func_parameter[,…]])
  13.  
  14. RETURNS type
  15.  
  16. [characteristic …] routine_body

Return statement is included in the syntax for a function and it specifies the return type of the function. Routine body is included to define a valid SQL statement. The syntax contains characteristic to provide information regarding nature of data. This may include attributes like CONTAINS SQL, NO SQL, READS SQL DATA and MODIFIES SQL DATA.

Alter Procedure

This statement is used to modify or alter the characteristics possessed by a stored procedure. Here is the syntax:

  1.  
  2. ALTER {PROCEDURE | FUNCTION} sp_name [characteristic …]

It offers you the advantage to bring in more than one change in the characteristics of stored procedures.

Drop Procedure

In order to remove a stored procedure, there is provision of DROP statement in MySQL database. The syntax for this takes the following shape:

  1.  
  2. DROP {PROCEDURE | FUNCTION} [IF EXISTS] sp_name

IF EXISTS is used to check the existence of specified procedure or function. It saves the statement from generating an error in case the procedure or function doesn’t exist.

Other Statements For Procedures

Apart from those mentioned above, there are other statements used for stored procedures. Here is the list o these statements:

  • Show Create Procedure – It is used to return the text of a stored procedure, which was defined previously using Create syntax. In the similar manner, there is Show Create Function statement to accomplish this task for stored function.
  • Show Procedure Status – It is used to return the characteristic of the specified stored procedure. These characteristics include name, type, creation date and so on. You may use Show Function Status also.
  • CALL – It is used to invoke the stored procedure created using Create Procedure statement.
  • Begin End – It is used to specify multiple statements for carrying out different types of operations and executions.
  • Declare – It is used to help programmers in declaring and defining local variables, conditions, procedures and so on.
  • SET – This statement is used to modify the values of local as well as global variables.

Also, there are condition statements like IF THEN ELSE, WHILE, CASE WHEN amongst others, which could be employed to operate these procedures.

Thus, MySQL stored procedures are tools for better performance, secure environment, providing ease of maintenance and also, for optimization.

on Jun 18th, 2008Related Posts Wordpress Plugin - Improve Your Blog SEO

The ‘Related Posts’ wordpress plug-in can be used to link other relevant posts with our own anchor text.

First you need to choose the source page or post as given in the below picture:

Related Post WP Plugin

Then add your desired anchor text:

Related Post WP Plugin

Then add your alt text if you need

Then choose the destination post:

Related Post WP Plugin

That’s all, look at the bottom of that source post:

Related Post WP Plugin

Download This Plugin


on Jun 10th, 2008Using session in PHP

Keeping in mind the fact that Internet is a stateless platform and every request for a web page is treated as unique, there is a serious need of a tool to maintain the state. Otherwise, it will be a messy situation to keep track of requests made by a particular user. The good news is that use of PHP session serves the solution to this problem. This session variable is of great importance for web applications like shopping carts and is considered as equivalent to cookies, other significant way of maintaining the state.

What Is PHP Session Capable Of

PHP session is capable of storing the information in the form of session variables, in order to handle the ever-increasing traffic on a website. For instance, consider a shopping website, with products scattered in different categories and different pages. In such a situation, a user may switch from one page t another and keep on adding products from different pages to his or her shopping cart.

Thus, in order to keep the track of a particular user on the shopping website, PHP sessions store user information and use it again and again. This is a powerful entity to serve the purpose for websites with huge customer base.

Getting Started With PHP Session

PHP session is initiated using following piece of code:

Now, suppose you visit a website in regular intervals in a specific period of time. The website must not treat you like a new user on every visit of yours. Rather, it must take the advantage of session variable to assign a user value to your first visit and use it again and again for every visit paid by you. Thus, we can add following code to accomplish this task:

  1. session_start();$_SESSION[‘counter’]++;
  2.  
  3. echo "Welcome Back! You have viewed this page " . $_SESSION[‘counter’] . " times";
  4.  
  5. ?>

Thus, if you revert to a particular website in short period of time, the counter will be incremented. If you visit the website 5th time, you might see it written somewhere that “Welcome Back! You have viewed this page 5 times”.

How Does It Work

Whenever you visit a web page, the PHP session sets information on your computer in the form of a cookie. It is generally a random key, formed by alphabets and numbers. In case, you visit another webpage of same website, the session explores the computer for a previously generated key. In case a match is found, that particular session is utilized. Otherwise, a new session is created with whole procedure related.

How To End A PHP Session

A session is destroyed with the help of following code:

  1.  
  2. ?>

It is a matter of fact that a session exists until and unless the associated user closes the browser used to open the website. Once the browser window is shut down, the session is destroyed. You may also decide the life of a session by bringing in following modifications in php.ini file.

session.cookie_lifetime = 0

You may change the value from zero to number of seconds you want a session to live.

You may also destroy a session variable using unset() or all session variable using session_unset().

on Jun 2nd, 2008MySQL Full-text Search Function

MySQL 4.0 has come up with a completely functional method to employ text searches on the table columns. In fact, the method known as full-text search function is capable of building a small search engine to conduct searches on CHAR, VARCHAR and TEXT columns. Though the function was added in the MySQL 3.23.23 version, but full capabilities of this function could be explored in MySQL 4.0.

Full-Text Search Defined

Suppose you want to create a table with few text fields like first name, last name and profile. You can provide space to mysql full-text functionality in the following manner:

  1.  
  2. CREATE TABLE person (id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,firstName VARCHAR(200),lastName VARCHAR(200),profile TEXT,FULLTEXT (firstName, lastName, profile)) Engine=MyIsam;

Alternatively, if you already have a table and want to add full-text functionality to it, you may follow a similar code as given below:

  1.  
  2. ALTER TABLE person ADD FULLTEXT (firstName, lastName, profile);

These lines help the MySQL to set up an index on text fields of firstName, lastName and profile. This enhances the capability of MySQL to refine its search criterions, whenever a user tries to search for textual data on a website.

After successful implementation of Full Text is done, one may follow the following syntax to carry out the search:

  1.  
  2. SELECT col1, col2 FROM tableWHERE MATCH (col1, col2) AGAINST (‘expression’);

The MATCH function specifies the name of the columns, for which a particular search is carried out. The AGAINST function is used to specify the value of the query to be searched. One may specify search modifier in this function to carry out Boolean Mode search and also, to use Query Expansion.

Example:
Let us assume that the above table contains the following data:

id firstName lastName profile
1 MySQL mysql MySQL is an open source RDBMS.
2 PHP Hypertext Preprocessor PHP is an open source server side programming language.
3 JavaScript js JavaScript is a client side scripting using this we can validate form data & can create lots of dynamic contents on the web page.

Run the following query to search the word ‘mysql’

  1.  
  2. SELECT *,MATCH(`firstName`,`profile`,`lastName`) AGAINST(‘mysql’) AS rel FROM `person` ORDER BY rel DESC

The output will be like this:

id firstName lastName profile rel
1 MySQL mysql MySQL is an open source RDBMS. 1.091023247894
2 PHP Hypertext Preprocessor PHP is an open source server side programming language. 0
3 JavaScript js JavaScript is a client side scripting using this we can validate form data & can create lots of dynamic contents on the web page. 0

Usage of Full-Text Function

Full Text function could be used at four main places:

  • Natural Language Searches, where search is carried out for a particular string against the text collection specified as Match parameters.
  • Boolean Mode Searches, using In Boolean Mode modifier and implied Boolean logic in the form of AND, OR and NOT.
  • Stopwords Full Text to ignore the noise words like THE, HAVE, SOME and so on.
  • Query Expansion Full Text search to automatically expand the range of words to be included in the search criterion. This means that once a search is carried out using a specific word, then the search is repeated and this time other words appearing significantly in the text collection are also included.

Some Points worth Mentioning

Here are few points, which are relevant to the usage of Full Text function:

  • This function employ case-insensitive search criterion.
  • Only MyISAM tables are incorporated in the search carried out by this function.
  • The search is carried out amongst the words with default length of 4 characters or more.
  • One may use ft_min_word_len and ft_max_word_len functions to specify the length of the search words.
  • For large data sets, it is advised to employ Full Text function after loading the data into the table.
  • Full Text search is incapable of working with some natural languages like Chinese and Japanese, which lack word delimiters.

Full Text search is good for large databases, where it is practically impossible to use LIKE and other MySQL methods.

on May 6th, 2008File Uploading in PHP

File uploading is very simple in PHP when comparing to other server side programming languages. File uploading is very useful in most of the situations like uploading user’s photos, uploading csv reports, uploading pdf reports and so on.

Making a simple front end with file browsing box:

  1.  
  2. <form method="post" enctype="multipart/form-data">
  3. Upload a file
  4. <input name="my_file" type="file" />
  5. <input value="Upload" type="submit" />
  6. </form>

Note: You should have this enctype=”multipart/form-data”‘ in your form tag while uploading files.
The php source code to upload the files

  1.  
  2. if(isset($_FILES[‘my_file’][‘name’]) &amp;&amp; $_FILES[‘my_file’][‘name’] != )
  3. {
  4. $upload_dir = ‘home/myaccount/public_html/images’;//uploading directory, this folder should have write permission to the current user
  5. $upload_file = $upload_dir.‘/’.basename($_FILES[‘my_file’][‘name’]);
  6.  
  7.   //check if the file name already exists
  8.    if(file_exists($upload_file))
  9.      {
  10.      echo "File Already Exists"; //if file already exists print the error message
  11.      }
  12.      else
  13.      {
  14.           if(move_uploaded_file($_FILES[‘my_file’][‘tmp_name’],$upload_file))
  15.              {
  16.              echo "File Uploaded";
  17.              }
  18.             else
  19.             {
  20.             echo "There was a problem to upload file";
  21.             }
  22.      }
  23. }
  24. ?>

on Apr 17th, 2008Generating CAPTCHA Image Using PHP

The CAPTCHA concept is very useful to prevent automated registration. If you have enabled gd library, you can create a captcha code for your registration form using PHP.

Consider the following parts of code, name the file as "captcha.php"

session_start();

if(isset($_SESSION[‘captcha’]))
{
unset(
$_SESSION[‘captcha’]);
}

The above code will start session and clear the old captcha’s session value if it set.

$num_chars 5//number of characters for captcha image
$characters array_merge(range(0,9),range(‘A’,‘Z’),range(‘a’,‘z’)); //creating combination of numbers & alphabets
shuffle($characters); //shuffling the characters

The above part of code describes the number of captcha characters and total available characters, here I am using all the lower and upper case alphabets and all numerics.
//getting the required random 5 characters
$captcha_text "";
for(
$i=0;$i<$num_chars;$i++)
{
$captcha_text .= $characters[rand(0,count($characters)-1)];
}

$_SESSION[‘captcha’] = $captcha_text// assigning the text into session

This part of code generated the required captcha code in a random manner from the available character array, also It assigns the value to session variable.

header("Content-type: image/png"); // setting the content type as png
$captcha_image imagecreatetruecolor(14030);

$captcha_background imagecolorallocate($captcha_image225238221); //setting captcha background colour
$captcha_text_colour imagecolorallocate($captcha_image589447); //setting cpatcha text colour

imagefilledrectangle($captcha_image0014029$captcha_background); //creating the rectangle

$font ‘Arial.ttf’//setting the font path

imagettftext($captcha_image2001121$captcha_text_colour$font$captcha_text);
imagepng($captcha_image);
imagedestroy($captcha_image);

The remaining code will draw the image.

How to use this captcha?

It’s simple, in your registration form put this part of code:

<img src="captcha.php">

Then you can put a text box to enter the captcha value, and then you can compare the entered captcha value with the assigned captcha session value.

 

on Mar 29th, 2008PHP Interview Questions and Answers

Question: Is PHP a case sensitive programming language?

Answer: PHP is a partially case sensitive programming language. We can use function names, class names in case insensitive manner.

Question: What is mean by LAMP?

Answer: LAMP means combination of Linux, Apache, MySQL and PHP.

Question: How do you get the user’s ip address in PHP?

Answer: Using the server variable: $_SERVER[’REMOTE_ADDR’]

Question: What is the difference between require and include?

Answer: When using require function to embed another file in php, it will give fatal error if the file is not exists.
        When using include function to embed another file in php, it will give warning if the file is not exists.


Question: How to find the number of elements in an array?

Answer: Using count($array) or sizeof($array).

Question: How do you make one way encryption for your passwords in PHP?

Answer: Using md5 function or sha1 function

Question: How do you get ASCII value of a character?

Answer: By using ord function.

on Mar 20th, 2008Email validation using PHP regular expression

Regular expression is a wonderful concept, using this we can play with strings in PHP. The practical use of regular expression is:

  • Email validation
  • validating domain name
  • validating post code format etc.

There are two types of regular expression functions:

  1. ereg functions or POSIX extended regular expression function, which is the standard functions for PHP
  2. preg functions or perl Compatible regular expressions

For this email validation program, we are going to use PHP’s standard regular expression function "ereg".

Before entering the email validation program, its better to refer few basic syntax about regular expression functions.

\s -> this means an empty white space
^ -> this means start of a string
$ -> this means end of a string
. -> this means any character
(cat|mat) -> this means cat or mat
[0-9] -> this means all numbers from 0 to 9 inclusive
[a-z] -> this means all lowercase letters from a to z inclusive
[A-Z] -> this means all uppercase letters from A to Z inclusive
[^a-z] -> this means no occurrence of lowercase letters from a to z inclusive, the hat symbol (^) inside the sets denotes "not"
? -> this means zero or one of the proceeding characters
* -> this means zero or more characters
+ -> this means one or more characters
{3} -> this means exactly three characters
{3,} -> this means three or more characters
{3,6} -> this means 3 to 6 characters, it may be 3 or 4 or 5 or 6

Here is the php source code for email validation using php regx function:

<?php
$email 
"myemail@mydomain.com";

if (ereg(‘^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$’,$email)
{
echo 
‘Valid email id’;
} else {
echo 
‘Invalid email id’;
}
?>

Now I am going to split the string pattern into 3 parts, ie

1] ^[a-zA-Z0-9._-]+@
2] [a-zA-Z0-9._-]+\.
3] ([a-zA-Z]{2,4})$

1]^[a-zA-Z0-9._-]+@

Here ^ symbol denotes that this is the start of the email part.
a-zA-Z0-9._- denotes combination of characters to form the username section of an email
+ symbol denotes, it should have 1 or more characters from the proceeding sets
@ symbol is a default symbol between username and domain name parts.

2] [a-zA-Z0-9._-]+\.
a-zA-Z0-9._-  denotes combination of characters to form the domain name without the tld
+ symbol denotes, it should have 1 or more characters from the proceeding sets
\. symbol denotes, the dot operator proceeding to the tld, here we are using \ to escape

3] ([a-zA-Z]{2,4})$

a-zA-Z denotes the combination of chars to form the tld name
{2,4} denotes the length of the tld may be between 2 to 4 characters
$ denotes the end of an email.

on Mar 12th, 2008Recursive function in PHP

recursive function is a function that calls itself repeatedly for a specified condition.
Here is an example function which calls iteself to perform a tree structure for a category table
Here is the category table:

category_id parent_id category_name
1 0 CMS
2 0 Blogs
3 0 Forums
4 0 E-Commerce
5 1 Joomla
6 1 Mambo
7 6 Templates
8 6 Mods/Components
9 4 OSCommerce
10 2 Wordpress
11 10 Themes
12 10 Plugins

<?php echo ‘<select name="category">
<option value=’
0‘>Root</option>’;
$allcats getTree();
foreach(
$allcats as $key=>$value)
{
echo 
"<option value=’$key’>$value</option>"
}
echo 
‘</select>’;

function getTree($id=0)
{
static 
$cates = array();
static 
$times 0;
$times++;
$result mysql_query("SELECT category_id,category_name FROM category_table WHERE parent_id=$id ORDER BY category_name"); 
   while(
$row mysql_fetch_assoc($result))
    {
         
$cates[$row[‘category_id’]] =  str_repeat("|&nbsp;&nbsp;&nbsp;",$times-1)."|___".$row[‘category_name’];
        
getTree($row[‘category_id’]);
     }
 
$times—;
 return 
$cates;
 }  
 
?>

The out put of this program would be the following select box:

 

on Mar 12th, 2008Installing PHP 5 and apache on windows xp.

PHP is best suited for LAMP [Linux, Apache, MySQL and PHP] environment, but we can use in WAMP [Windows, Apache, MySQL and PHP] environment also, here are the options to install & configure php with apache in windows machines.

1] Use WAMP Server or XAMPP server for one click installation, no need for configuration.
2] Manually install and configure apache & php.

The first option is very easy, you can download a windows set up package from their site and can install in a single click.

Here are the steps for installing apache and php manually in a windows machine:


1] Download apache for windows from http://www.apache.org/

2] Install it.

3] Create your document root folder [Which will be accessed like http://localhost/], for example I am going to create this under C drive ie "C:\myprojects"

4] Now open the apache http configuration file[httpd.conf]

5] Search for  DocumentRoot, replace the old value by "C:\myprojects", Also set <Directory     "C:\myprojects">

6] Now save the file and restart the apache web server.

7] Open your browser and type "http://localhost/", now you can see apache working.

8] Download the latest PHP [Normal package without installer] from http://www.php.net/

9] Extract it under C drive ie, the "C:\php"

10] Again open the apache http conf file, and search for "ScriptAlias", add the following to work php
ScriptAlias /php/ "c:/php/"
11] Then add
AddType application/x-httpd-php .php and Action application/x-httpd-php "/php/php-cgi.exe"
12] Restart apache
13] Create an "index.php" file under "C:\myprojects", with the following code
‘); ?> 14]Open your browser, and type http://localhost, now you can see php is working..