Archive for February, 2010


Here we are going to see basic AJAX script in play. Here I’m writing a script which populates a drop down box with states according to the countries selected in another drop down. So let’s see how it is done.

Given below are the drop downs in play (Note: I’ve only used a few data)

Country: <select name="country" onchange="return onchangeajax(this.value);" >
 <option value=""   selected="selected" >Select</option>
 <option value="USA"  >USA</option>
 <option value="India"  >India</option>
 <option value="UK"  >UK</option>
 </select><br />
 State: <div id="statediv"><input type="text" name="state" /></div>
 <input type="submit" name="signupsubmit" value = "Sign Up" />

Now as we see we have written a JavaScript function call on changing the items in drop down. Given below is the Ajax code to be embedded in the page.

function onchangeajax(pid)
 {
 xmlHttp=GetXmlHttpObject()
 if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }

 var url="changestate.php"
 url=url+"?pid="+pid
 url=url+"&sid="+Math.random()
 document.getElementById("statediv").innerHTML='Please wait..<img border="0" src="images/ajax-loader.gif">'
 if(xmlHttp.onreadystatechange=stateChanged)
 {
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)
 return true;
 }
 else
 {
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)
 return false;
 }
 }

 function stateChanged()
 {
 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("statediv").innerHTML=xmlHttp.responseText
 return true;
 }
 }

 function GetXmlHttpObject()
 {
 var objXMLHttp=null
 if (window.XMLHttpRequest)
 {
 objXMLHttp=new XMLHttpRequest()
 }
 else if (window.ActiveXObject)
 {
 objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
 }
 return objXMLHttp;
 }
</script>

Now we see that in the Ajax script it is calling another file ‘changestate.php’. This is the file which has the code that should populated in the ‘statediv’

<?php
 $val=$_REQUEST['pid'];
 if($val == 'USA')
 {
?>
<select name="state">
 <option value="">--Select--</option>
 <option value="Alabama">Alabama</option>
 <option value="Alaska">Alaska</option>
</select>
<?php
 }
 else if($val == 'India')
 {
?>
<select name="state">
 <option value="">--Select--</option>
 <option value="Karnataka">Karnataka</option>
 <option value="Kerala">Kerala</option>
</select>
<?php
 }
 else
 {
?>
<input type="text" name="state" />
<?php
 }
?>

[/sourcecode]

Here is an example of  how to use pagination in your PHP oage. I’m using a pagination class developed by Shiege Iseng’ and can be downloaded from here.

We include this file in the page we use. So here is a basic script that shows the details of users from a database and shows 4 of them in a pagae and shows 3 pages as links in between the [prev] and [next] links.


<?php

//making the database connection
include_once('includes/connection/connection.inc');
 dbConnect();

//including the paging class
 require_once('paging_class.php');

//database query
 $qry = "SELECT * FROM USERS";
 $results = mysql_query($qry);
 $num_rows = mysql_num_rows($results);

//making a paging object that shows 4 results and 3 links
$paging = new paging(4,3);
 $paging->db($host,$username,$passwd,$dbName);
 $paging->query($qry);
?>

<html>
 <head>
 <title>Pagination Example</title>
 </head>

<body>

<table>
 <tr>
 <td>Total Results Found: <?php echo $num_rows; //prints total results ?></td>
 </tr>
 <tr>
 <td>Sl No</td>
 <td>First Name</td>
 <td>Last Name</td>
 <td>Sex</td>
 <td>DOB</td>
 <td>Email</td>
 </tr>

 <?php
 $sl = 1;
 $pageno = 1;
 $pageno = $pageno - 1;
 if($pageno > 0)
 $s1 = $pageno * 10;
 else
 $s1 = 0;
 ?>

 <?php
 if($num_rows > 0)
 {
 $i = 1;
 while($obj=$paging->result_assoc())
 {
 $s1 = $s1 + 1;
//to alternate b/w colors in the row
 if(($i + 1) % 2 == 0)
 $bgcolor="#dbe3f0";
 else
 $bgcolor="#dbdcf0";
 ?>

 <tr bgcolor="<?php echo $bgcolor?>">
 <td><?php echo $sl; ?></td>
 <td><?php echo $obj['firstname']; ?></td>
 <td><?php echo $obj['lastname']; ?></td>
 <td><?php echo $obj['sex']; ?></td>
 <td><?php echo $obj['dob']; ?></td>
 <td><?php echo $obj['email']; ?></td>
 </tr>

 <?php
 $i++;
 }
 }
 else
 {
 ?>

 <tr>
 <td>No Data Available !! Please redifine your Search.... </td>
 </tr>

 <?php
 }
 ?>
 <tr>
 <td><?php echo "<hr>".$paging->print_link();?></td>
 </tr>

 </table>

Sending Mail

Sending mail using PHP is very simple. Here I’ll show how we can send the activation mail to a registered using along with the verification key we generated in last post.

<?php
    $emailto= "recipient@example.com";
    $frmname="yourid@yoursite.com";
    $subject	= "Activation-yoursite.com";
    $min_size	= "1";
    $max_size	= "4000";
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $headers .="To:".$emailto."<".$emailto.">\r\n";
    $headers .="From:".$frmname."<".$email.">\r\n";
    $headers 	= "From: yourid@yoursite.com";
    $message	= "Registration Successfull!!\n\nThank you for registering with us. \n\nUser name: ". $username . "\nPassword: ". $password ."\n\n Click here for activation.\n www.yoursite.com/activate.php?verikey=".$pass;
   $ok = @mail($emailto, $subject, $message, $headers);
   $msg	= "Registered Successfully";
   header("location:register_suc.php?msg=$msg");
?>

This will send the recipient with the username and password along with the verification key generated instructing them to click on the link to activate their profile. We will see how to implement the activation page in this post. We also need to understand how to first add the generated key to database.

Actually adding the generated key to database is as easy as any other PHP-MySQL queries. I’ll just give an example here.

$qry = "INSERT INTO users (name, password, email, vkey) VALUES ('$uname', '$passwd', '$email', '$pass');
mysql_query($qry);

We’ll be having a field in the ‘users‘ table named ‘status‘ which is by default ‘N’. The purpose of the activate page is set this to ‘Y‘. It is really very easy. Here is the code in the ‘activate.php‘ page.

$verikey = $_GET['verikey'];
 $qry = "UPDATE users SET status = 'Y' WHERE vkey = '$verikey'";
 mysql_query($qry);

While registering with a website we often need to verfy our email id. Given below is the code to develop that functionality. The following will generate the verification key which has 6 characters

function generatePassword()
{
    $length =6;
    $validchars = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    $password ="";
    $counter = 0;

    while($counter < $length)
    {
        $actChar = substr($validchars, rand(0, strlen($validchars)), 1);

        if(!strstr($password, $actchar))
       {
           $password .= $actChar;
           $counter++;
       }
   }

   return $password;
}

rand(0, stlen($validchars)) – generates a random number between 0 and the length of $validchars (inclusive of both ends).

substr($a, $b , len) – get generates a sub string from $a from the first occurrence of $b to length specified by len.

strstr($a, $b) – checks whether $a has $b in it. This is done to create unique characters.

So this is how you generate random string. How you can use it for verification purpose of a user registration is explained in the subsequent posts.

This is very very novice kind of thing. Every web application requires script like this. Usually we write the following in a file named connection.inc which would later be included in files as needed.

$host = "localhost";
$dbname = "database_name";
$username = "user";
$password = "pass";

function dbConnect()
{
    global $host, $username, $password, $dbname;
    mysql_pconnect($host, $username, $password) or die("Error connecting to database");
    mysql_select_db($dbname) or die("Cannot select the database");
}

mysql_pconnect() makes a persistent connection. When connection it listens for any open connections and uses it if available. Also once the script ends it won’t close the connection. It will remain open for any further connections. It cannot also not closed with mysql_close() function.