Form Validation in php

To validate the input provided by the user from form is a common requirement now days. For example, it must be check 

  1.  mandatory fields must be properly filled
  2.  age must contain numeric value
  3. email provided by user must be a valid email
  4. Date of Birth must be a valid date.

These are just examples to tell you how the data of the form should be validated.  

Most of the web developer just uses javascript to validate the form data. Javascript is a client side language and interpreted on client's computer and it is interpreted by web browser such as Internet Explorer, Firefox, Opera, Google Chrome, etc. If javascript code is properly written to validate the form data then user cannot go to next page unless he/she provides the correct data. But javascript has a major drawback and its drawback is IF JAVASCRIPT IS DISABLE IN WEB BROWSER THEN USER CAN ENTER ANY VALUE WHAT HE/SHE WANTS AND YOUR DATABASE CAN BE DEMAGED DUE TO THE DATA PROVIDED BY THE USER. So it is better to validate the form data by using client side language(javascript) as well as server side language such as PHP, so incase if javascript is disable then server side validation prevents the user to enter the wrong data and restrict user to provide valid data.

Form Validation in php

I am going to develop a php page that just contains a form and after hitting the submit button I will validate the data provided by user using PHP.


<html>
<head>
<title>Form Validation</title>
<style type="text/css">
.fontclass{font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
}
</style>
</head>
<body>
<table cellpadding="2" cellspacing="2" class="fontclass">
<tr>
<form name="form1" method="post" action="verify.php">
<tr>
<td><strong>First Name</strong></td><td><input type="text" name="fname" /></td>
</tr>
<tr>
<td><strong>Last Name</strong></td><td><input type="text" name="lname" /></td>
</tr>
<tr>
<td><strong>Email Address</strong></td><td><input type="text" name="email" /></td>
</tr>
    <tr>
      <td><strong>Username</strong></td>
      <td><input type="text" name="username" /></td>
    </tr>
      <tr>
    <td><strong>Date</strong></td>
    <td><input type="text" name="date_user" size="10" /> (mm/dd/yy)</td>
  </tr>
    <tr>
<td><strong>Age</strong></td><td><input type="text" name="age" size="10" />
</td>
</tr>
<tr>
<td> </td><td><input type="submit" value="Submit" /></td>
</tr>
</form>
</tr>
</table>
</body>
</html>

The above code will generate a webpage that contains a web form containing six fields, snap shot of that web page is provided below.





action attribute of form(action="verify.php") contains the name of the web page in which i have written php code to validate the form data. Here's the code to validate the form data.

Verify.php

<?php
$fname=trim($_POST['fname']);
$lname=$_POST['lname'];
$email=trim($_POST['email']);
$age=trim($_POST['age']);
$date_user=trim($_POST['date_user']);
$username=trim($_POST['username']);
$age_len=trim(strlen($age));

if(empty($fname))
{
header("location:form.php?msg=pleaseenteremail");
}

//Now email validation using Regular Expressions
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){ 
header("location:form.php?msg=emailnotvalid");
}

//Now performing numeric data validation for Age Field
if(!is_numeric($age))
{
header("location:form.php?msg=agenotvalid");
}

//Now checking the length of the data provided by user as his/her age
if($age_len>3)
{
header("location:form.php?msg=agenotvalid");
}

//Now performing Date Validation for Date Field
$arr=split("/",$date_user); // splitting the array
$mm=$arr[0]; // first element of the array is month
$dd=$arr[1]; // second element is date
$yy=$arr[2]; // third element is year
if(!checkdate($mm,$dd,$yy)){
header("location:form.php?msg=datenotvalid");
}

?>
trim() function is used to remove the spaces before and after the data.

empty() function is a Boolean function that checks whether the data in the form of its argument is empty or not?

is_numeric() function is also a Boolean function that returns whether the data in the form of its argument is numeric or not?

strlen() function provides the length of the string.

checkdate() function is a built in function that checks whether date provided is valid or not. It also takes care of leap year checking. It is also a Boolean function and return true if date is correct and return false if date is false.

Now let's understand the code that is performing validation of form data.

First of all I am getting form data using $_POST because form data coming from previous page is using the post method. Then i remove extra spaces to the form data by using trim() and assign that data to the different variables.

 

$age_len=trim(strlen($age));

for checking the length of age data, i first of all remove the extra spaces before/after the age data provided by the user and then check the length of age data using strlen() function.

 

if(empty($fname))

{

header("location:form.php?msg=pleaseenteremail");

}

Then i check whether the first name is empty or not. If empty then returns to the prevous page with a query string that indicates the error.

if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){ 

header("location:form.php?msg=emailnotvalid");

}

To validate email address, i use regular expression. Again if email is not a valid email then I redirect page to the previous page with a query string.

 

if(!is_numeric($age))

{

header("location:form.php?msg=agenotvalid");

}

To check whether age provided is numeric or not i use the is_numeric() function because age can be numeric like 23 not the characters abc.

To perform date validation i use the built in php Boolean function which is checkdate() that takes three arguments which is month, day and year. Now its up to you whether you provide date like this way 02/10/09 or like this way 02/10/2009, this powerful built in function can validate both form of dates. To get month, day and year from the date provided by the user I use split() function to split the date and get the month, day and year and then provide these three to checkdate() function to validate the date.

So this is a practical example to perform form validation in php.

 

 

Read more...

Updating records in php

In this php tutorial we will learn how to update records in php using database of mysql. To update records in php is quite easy, let's have a look over below mentioned example to learn how to update records in php.

edit-recs.php


=========(Code)edit-recs.php=========

<?php
require_once('conn.php');
$select_query="select * from student";
$result=mysql_query($select_query);
?>

<body>
<table width="100%" cellpadding="2" cellspacing="2" class="fontclass">
<tr>
<td width="12%">
<strong>Roll No</strong></td>
<td width="16%">
<strong>First Name</strong></td>
<td width="20%">
<strong>Last Name</strong></td>
<td colspan="2">
<strong>Father Name</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result))
{
?>
<tr>
<td width="12%">
<?php echo $rows['rollno'];?></td>
<td width="16%">
<?php echo $rows['fname'];?></td>
<td width="20%">
<?php echo $rows['lname'];?></td>
<td width="12%">
<?php echo $rows['fathername'];?></td>
<td width="40%"><strong><a href="update-recs.php?rollno=<?php echo $rows['rollno'];?>">Edit</a></strong></td>
</tr>
<?php
}
?>
</table>
</body>

update-recs.php



=========(Code)update-recs.php=========
<?php
require_once('conn.php');
$rollno=$_GET['rollno'];
$select_query="select * from student where rollno='$rollno'";
$result=mysql_query($select_query);
$rows=mysql_fetch_array($result);
?>

<table width="600" cellpadding="2" cellspacing="2">
<tr>
<form name="form1" method="post" action="do-update.php">
<tr>
<td>First Name</td><td><input type="text" name="fname" value="<?php echo $rows['fname'];?>"/></td>
</tr>
<tr>
<td>Last Name</td><td><input type="text" name="lname" value="<?php echo $rows['lname'];?>" /></td>
</tr>
<tr>
<td>Father Name</td><td><input type="text" name="fathername" value="<?php echo $rows['fathername'];?>" /></td>
</tr>
<tr>
<td><input type="hidden" name="rollno" value="<?php echo $rollno;?>" /></td><td><input type="submit" value="Update Records" /></td>
</tr>
</form>
</tr>
</table>

do-update.php

<?php
require_once('conn.php');
$rollno=$_POST['rollno'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$fathername=$_POST['fathername'];
$sql="update student set fname='$fname',lname='$lname',fathername='$fathername' where rollno='$rollno'";
$result=mysql_query($sql);
if($result)
{
header("location:display.php");
}
else{
mysql_error();
}
?>


So this is the way to update records in php. Read more...

Getting complete web page url from address bar in php

In this tutorial you will learn how to get full web page url from address bar.

<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>

We are using these two php functions to get complete web page url from address bar. These two functions are
  1. $_SERVER['HTTP_HOST']
  2. $_SERVER['REQUEST_URI']
$_SERVER['HTTP_HOST'] this builtin php function will show you only server name, e.g www.yoursite.com .
$_SERVER['REQUEST_URI'] this builtin php function will show you the path to file of your url e.g www.yoursite.com/yourpage.php

So this is the way to get complete web page url from address bar in php

Read more...

Storing data in notepad or in ms word

In php you can store data in text file such as notepad and even in microsoft word too.

The following code will make you able to store form data(user name in my example ) in microsoft word file. It will create ms word file too that if file is not created before.

<?php
$username = $_POST['username'];
$fp = fopen("myfile.doc","a+") or exit("unable to open the file");
if($fp != null)
{
fwrite($fp,$username);
}
fclose($fp);

?> Read more...

Pagination with php

Pagination is used to display results of your query over multiple pages, rather than displaying on just one page. Pagination prevents user to scroll the webpage. For example if your query is bringing 1000 rows and you want to display these rows in php page then it will be done quite fine but it will disturb the user alot because he/she will tired after scrolling the page Repeatedly.

So to display records properly and to avoid scrolling, we use pagination. So let's look how we can do pagination with php.

*******Pagination.php*********



This is what i want to developed. This pagination offers the facility to Move Next Page, Previous Page, First Page and Last Page.

Pagination.php

<?php
require_once('conn.php');


// how many rows to show per page
$rowsPerPage = 15;

// by default we show first page
$pageNum = 1;

// if $_GET['page'] defined, use it as page number
if(isset($_GET['page']))
{
$pageNum = $_GET['page'];
}

// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;

$query = "select * from student" .
" LIMIT $offset, $rowsPerPage";
//print $query;
$result=mysql_query($query);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Pagination in php</title>
<style type="text/css">

.fontclass
{font-family:Verdana;
font-size:12px;
}

</style>
</head>
<body>
<table width="100%" cellpadding="2" cellspacing="2" class="fontclass">
<tr>
<td width="12%">
<strong>Roll No</strong></td>
<td width="16%">
<strong>First Name</strong></td>
<td width="20%">
<strong>Last Name</strong></td>
<td colspan="2">
<strong>Father Name</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result))
{
?>
<tr>
<td width="12%">
<?php echo $rows['rollno'];?></td>
<td width="16%">
<?php echo $rows['fname'];?></td>
<td width="20%">
<?php echo $rows['lname'];?></td>
<td width="12%">
<?php echo $rows['fathername'];?></td>
<td width="40%"><strong><a href="delete-rec.php?rollno=<?php echo $rows['rollno'];?>">Delete</a></strong></td>
</tr>
<?php
}
?>
</table>

<?php
$query = "SELECT COUNT(rollno) AS numrows FROM student";

$result = mysql_query($query) or die('Error, query failed');

$row = mysql_fetch_array($result, MYSQL_ASSOC);

$numrows = $row['numrows'];

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);

// print the link to access each page
$self = $_SERVER['PHP_SELF'];

// creating previous and next link
// the first and last page
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " <a href=\"$self?page=$page\">[Prev]</a> ";
$first = " <a href=\"$self?page=1\">[First Page]</a> ";
}
else
{
$prev = ' '; // we're on page one, don't print previous link
$first = ' '; // nor the first page link
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " <a href=\"$self?page=$page\">[Next]</a> ";
$last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> ";
}
else
{
$next = ' '; // we're on the last page, don't print next link
$last = ' '; // nor the last page link
}
// print the navigation link
echo $first . $prev .
" Showing page $pageNum of <B>$maxPage</B> pages " . $next . $last;
?>


</body>

</html>


Explaination

$rowsPerPage = 15;
I am specifying number of rows that will be shown per page .

$pageNum = 1;
By default i will show first page.


if(isset($_GET['page']))
{
$pageNum = $_GET['page'];
}

if page number is coming from query string then i will display that page. Else by default we will show first page.

$offset = ($pageNum - 1) * $rowsPerPage;
Counting the offset, offset is the main thing in whole pagination process. Offset is an integer indicates the distance from beginning until a given element or point.

$query = "select * from student" .
" LIMIT $offset, $rowsPerPage"

Then i apply limit on my query, the above query will look like same if you print it
select * from student LIMIT 0, 15 it means to display number of records that lies in the given range.

After this i am executing the query and displaying rows one by one from result set.

Now again look at some important code snippet in pagination module. After while loop we are counting total number of records by executing this query
$query = "SELECT COUNT(rollno) AS numrows FROM student";
and then i find out the max page, means how many pages will become during whole pagination process and then i find out the first, previous, last and next pages and display them in a proper manner where they need to display.

Read more...