Thursday, November 4, 2010

Prevent Multiple Submission of the Same Form

In this post I would like to suggest a way to guard against resubmitting the same form. If you don't have an option in your code, to prevent the same form from resubmitting then you can identify that your database is just filled with the same data.

We can point variety of reasons for resubmission the same form. Double clicking the submit button, hit their browser back button to edit or recheck the form and hit the submit button again are some examples.

You can place a unique Id in your form by using PHP uniqid() function, like shown below.

$unique_id = uniqid(microtime(), 1);
echo ''; //place this line your form to have a hidden field.



When saving the form data check whether the form is already saved in the database or not by checking the unique_id like below. If the unique_id is not exist then you save the form data in the database and the unique_id beside the form data.


$unique_id = $_POST['unique_id']; // I assumed that the form is submitted by post method.

$query = "SELECT * FROM your_table_name WHERE unique_id = '".$unique_id."'"; //in your table you need a column named unique_id.
$result = mysql_query($query);
if(mysql_num_rows($result)){
   //if true, the form is already submitted. Don't save.
}else{
   // save the form
}


Tuesday, October 26, 2010

Javascript function Equivalent to PHP explode() function

We can explode a string into an array using the PHP explode() function. The javascript equivalent function is split() which is slightly different from PHP explode().


PHP explode() function works like this.

$longstring = "codesbyme.blogspot.com";
/**
* we are dividing the string by the dot(.). instead of the dot
* you can have any character which is in your string
* Eg: space, @, #, etc...
$words = explode(".", $longstring); // now $words is an array.

echo $words[0]; //prints "codesbyme"
echo $words[1]; //prints "blogspot"
echo $words[2]; //prints "com"

Now lets see how is the Javascript split() function works. The syntax of this function is slightly different from the PHP explode().

var longstring = "codesbyme.blogspot.com";
var words = longstring.split('.');

/*
words[0] = codesbyme
words[1] = blogspot
words[2] = com
*/

Monday, October 25, 2010

Simple Form with PHP and Ajax

In this post I will explain how to work with a simple form and the submitted form data is handled by PHP. I think this may helpful for the beginners.

In this example I have used javascript to validate the form and used bit of ajax.
By using ajax I am checking the database if the username or the email is already been used. If so an error message will be shown.

I hope to keep this example very clear and simple as much as possible.

I am using MySql database in my example and to run this example first you need to create a database, named “form” and in that database create a table, named “register” which has three columns as “name”, “username” and “email”.

Here you have the sql for that, just copy and paste the code in your mysql prompt and run it.
CREATE DATABASE `form`;
USE `form`;
CREATE TABLE IF NOT EXISTS `register` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(256) NOT NULL,
  `username` varchar(256) NOT NULL,
  `email` varchar(256) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

And then lets create our form.
http://codesbyme.blogspot.com


A free example

Name:
Username:
Email:

Now we have our database and html form is ready. Name the html page as "form.html". Now lets code a javascript file which includes the ajax functionality and the a function to validate the form fields. Remember that you need to call this "form.js" file into the html page. To do that simply place this line of code in your html head tag.

Here is our "form.js" javascript file.

/**
 * validate the form before submit
 * @return boolean
 */
function validate(){
 var form = document.myform;
 var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; //regular expression for a valid email address
 
 if(form.name.value == '') //check name field is empty
 {
  alert("Please provide your name");
  form.name.focus();
  return false;
 }else if(form.uname.value == '')//check username fiel is empty
 {
  alert("Please provide a username");
  form.uname.focus();
  return false;
 }else if(form.email.value == '')
 {
  alert("Please provide your email");//check email field is empty
  form.email.focus();
  return false;
 }else if(!(form.email.value).match(emailPattern))//if the email field is not empty, then match the email address with the emailPattern
 {
  alert("Please provide a valid email address");
  form.email.focus();
  return false;
 }
}

/**
 * send a sever request through ajax to
 * check the username or email is already used
 * @param fieldname - name of the form field
 * @param val - value of the form field
 * @return
 */
function searchdata(fieldname, val){
 document.getElementById('ajax_message').innerHTML = '';
 var xhr = getXHR(); //call the getHXR function to  have the suitable Ajax object 

 xhr.onreadystatechange = function() { //this function will execute when the on ready state is changed
  
  
  if (xhr.readyState == 4 && xhr.status == 200) { //if the status is 200 (completed), execute the below codes
   
   //alert(xhr.responseText);
   //var output = xhr.responseText;
   document.getElementById('ajax_message').innerHTML = xhr.responseText; //set the response from the server to the html ["ajax_message" is the id of the html element]
       
   
  }
  
  
 };
 xhr.open("GET", "form.php?"+fieldname+"="+val, true); //method is get, and set the url
 xhr.send(null);
}

/**
 * creates an ActiveXObject for IE and
 * creates the HTTP Request object for Mozilla, Crome, Opera etc..
 * 
 * @return HTTP Request object or ActiveXObject according to the browser
 */
function getXHR() {
 var xhr = null;

 if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
 } else if (window.createRequest) {
  xhr = window.createRequest();
 } else if (window.ActiveXObject) {
  try {
   xhr = new ActiveXObject('Msxml2.XMLHTTP');
  } catch (e) {
   try {
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
   } catch (e) {
   }
  }
 }

 return xhr;
}

Ok. Now lets code our PHP script. Below you can see the php code for "form.php" file, which will handle all the server side tasks such as accessing the database, saving and fetching data from the database.

/**
 * A Free Example
 * @author Shakeel
 * @url http://codesbyme.blogspot.com
 */
class form{
 /**
  * constructor
  * @return void
  */
 function __construct(){

 }
 
 /**
  * set the database connection
  * @return mysql link resource
  */
 function dbconnect(){
  $connect = mysql_connect("localhost","root","");
  mysql_select_db("form", $connect);
  return $connect;
 }
 
 /**
  * This function is used to search 
  * the availabiity of username and email
  * @param $val
  * @param $ind - indicator, the $val is uname or email
  * @return html string
  */
 function search($val, $ind){
  $connect = $this->dbconnect(); //call the dbconnect function to connect to the database
  
  if($ind == 'uname')
  {
   $query = "SELECT * FROM register WHERE username = '".$val."'";
   $result = mysql_query($query, $connect);
   if(!$result){
    echo mysql_error($connect);
    exit;
   }
   $num_rows = mysql_num_rows($result);
   if($num_rows)
   {
    echo 'Sorry, the username is already has been used.';
   }else
   {
    echo 'Username is available.';
   }
   /*
    * mysql_free_result() will free all memory associated with the result identifier result. 
    * mysql_free_result() only needs to be called if you are concerned 
    * about how much memory is being used for queries that return large result sets. 
    * All associated result memory is automatically freed at the end of the script's execution.
    * --from http://www.php.net--
    */
   mysql_free_result($result);
  }else if($ind == 'email')
  {
   $query = "SELECT * FROM register WHERE email = '".$val."'";
   $result = mysql_query($query);
   if(!$result){
    echo mysql_error($connect); // print the mysql error if occured
    exit;
   }
   $num_rows = mysql_num_rows($result); //Get number of rows in result
   if($num_rows)
   {
    echo 'Sorry, the email is already has been used.';
   }else
   {
    echo 'Email is available.';
   }
   
   mysql_free_result($result);
  }
  
  /*
   * closes the non-persistent connection to the MySQL server that's associated with 
   * the specified link identifier
   * but this isn't usually necessary, 
   * as non-persistent open links are automatically closed at the end of the script's execution
   * --from http://www.php.net--
   */
  mysql_close($connect);
 }

/**
  * this function stores the form data in the database
  * @param $name
  * @param $uname
  * @param $email
  * @return html string
  */
 function store($name, $uname, $email){
  $connect = $this->dbconnect();
  
  $result = mysql_query("SELECT * FROM register WHERE username = '".$uname."'");
  if(!$result){
   echo mysql_error($connect);
   exit;
  }
  $num_rows1 = mysql_num_rows($result); //Get number of rows in result
  
  $result = mysql_query("SELECT * FROM register WHERE email = '".$email."'");
  if(!$result){
   echo mysql_error($connect);
   exit;
  }
  $num_rows2 = mysql_num_rows($result); //Get number of rows in result
  
  if($num_rows1){
   echo '

Sorry, The username is already has been used. Registration failed

'; exit; }else if($num_rows2){ echo '

Sorry, The email is already has been used. Registration failed

'; exit; }else{ $query = "INSERT INTO register(name, username, email) VALUES('".$name."', '".$uname."', '".$email."')"; if(mysql_query($query, $connect)){ echo '

Hi, '.$name.'. Your registration was successful

'; }else{ echo mysql_error($connect); } } } }//end of the class form $obj = new form();//create an instance of form class /* * below we are using $_GET[] to catch the form data, * becuase we are submitting the form data by using the "get" method. * if the "post" method is used,then $_POST[] should be used to catch the form data */ $name = $_GET['name']; $uname = $_GET['uname']; $email = $_GET['email']; $check = $_GET['check']; //If the value of check is 1, form is submitted. If the value of check is null the form data comes from ajax if($check){//if $check is not null ($check has a value) $obj->store($name, $uname, $email); // call the store function of form class to save the data in the database }else{ //if not call the search function of form class to check the username or email is already used if($uname){ $obj->search($uname, 'uname'); }else if($email){ $obj->search($email, 'email'); } }

One important thing is you must configure a local web server such as Apache, in your machine to run this tutorial.
Now we are almost done. You need to put all these files (form.html, form.js and form.php) into a single directory in your web root. Then access the form.html with a web browser by http://localhost/your directory name/form.html

Friday, October 22, 2010

WELCOME YOU ALL..!!!

Hi Friends,


Codes by Me is a result of my effort to help my friends, who interested in programming. Basically I publish code pieces of php, javascript, joomla, Mootools and JQuery. These codes are completely written by me and feel free to use anywhere in your work. Happy Programming and good luck.


Please note that this blog is just started and I will keep posting many of my codes continuously. So don’t forget to visit every day and to check what is new here or just subscribe you in my rss feeds. Don’t forget to leave your valuable feedbacks which may helpful to improve the site and I really appreciate them.


Thank you.