Translate

Saturday 27 September 2014

Update CSV FIle using explode & Sizeof array in PHP

Explaination:

1.While updating the csv file.one of the field in table as message:
  Advance Purchase Offer (Min LOS: 1) : Book 22 days in advance & get 10% discount on All Nights
  In this it seprated with : now we wnat to update it as three fields like offer,los,type
  in this three fields we have to update thi smessage as seprately.

2.Now what we have to do means use explode condition and we have update

3.  $message=explode(':', $messages);

4.First of all we have to get that message dats from table by using fetch condition
   
5.we have seprate this by using sizeof the array

6.If the size is 2 r 3 like that we have to write the condition and seprate that

7.$row['id']-->IS the table id

8.trim condition is used to remove the space

PHP Coding:

<?php
include('db.php');
$select=mysql_query("select * from tbl"); 
while($row=mysql_fetch_array($select)) {
        
        $messages=$row['Message'];

        $message=explode(':', $messages);

        if(sizeof($message) == 2) {
            $type = trim($message[0]);
            $offer= trim($message[1]);

            mysql_query("update tbl SET  offer='$offer',los='0',type='$type' where id= '".$row['id']."' ");
        } else {
            $deal_type = trim($message[0]);
            $los= trim($message[1]);
            $offer= trim($message[2]);

            $los = trim(str_replace(")", "", $deal_los));
            $type = trim(str_replace("(Min LOS", "", $deal_type));

            mysql_query("update tbl SET  offer='$offer',los='$los',type='$type' where id= '".$row['id']."' ");
        }
}
?>

Upload CSV file to Database using PHP

Explaination:

  1.We have connect to datadase.Then cretae  the table what are the fields is in the csv file
that names only we have to put into field name.

2.We have to check the condition for to upload CSV file to database.

3. $min = strtotime('2014-02-02');
$max = strtotime('2014-08-02');
$val = mt_rand($min, $max);
$string= date('Y-m-d H:i:s', $val);
The above Coding is used to display random date.

4.THen we will use For loop ahat are the datas in DB that has to been uploaded.

5.If there is any unexpected  string function in CSV file is not be uploaded so we will use
 str_replace(); function.
 $emapDatass[$i] = str_replace('"','',str_replace("'", "", $emapDatass[$i]));

6. If there is any ID means suppose in DB id is only one digit and you want to generate it has an 
   8digit means use str_pad();function.
   $VendorID = str_pad($emapDatass[1], 8, "0", STR_PAD_LEFT);

7. While inserting the data Just you put this variable where You want.  
   $sql = "insert into Tbl_name (`VendorName`,`VendorID`, `HotelClass`, `) 
    values('$emapDatass[0]','$VendorID','$emapDatass[2]',......)";          

Form:

 <form action="" method="post" enctype="multipart/form-data">
        <label for="file">Filename:</label>
        <input type="file" name="file" id="file"><br>
        <input type="submit" name="submit" value="Submit">
    </form>

PHP Coding:


<?php
include('db.php');
if(isset($_POST['submit']))
{
$fname = $_FILES['file']['name'];     
$chk_ext = explode(".",$fname); 
$filename = $_FILES['file']['tmp_name'];   
if($_FILES["file"]["size"] > 0)
{
if($chk_ext[1]=='xls' || $chk_ext[1]=='csv'  )//Check the Condition whether CSV or XLS file
{
$file = fopen($filename, "r");
$tot = 0;  
while (($emapDatass = fgetcsv($file, 10000, ",")) !== FALSE)
{
// Convert to timetamps
$min = strtotime('2014-02-02');
$max = strtotime('2014-08-02');
// Generate random number using above bounds
$val = mt_rand($min, $max);
// Convert back to desired date format
$string= date('Y-m-d H:i:s', $val);
if($tot!="0")
{
for($i=1;$i<=11;$i++) {
$emapDatass[$i] = str_replace('"','',str_replace("'", "", $emapDatass[$i]));
}
$VendorID = str_pad($emapDatass[1], 8, "0", STR_PAD_LEFT);
$sql =  $sql = "insert into Tbl_name (`VendorName`,`VendorID`, `HotelClass`,field_names.......) 
values('$emapDatass[0]','$VendorID','$emapDatass[2]','$emapDatass[3]',......)"; 
$result = mysql_query($sql);    
}
if(!$result)
{
$msg="Invalid File:Please Upload CSV File!!";
}
$tot++;
}
}
else
{
echo "<script>alert('Please check your flie extension');</script>"; 
echo "<script>window.location='upload_overview.php';</script>";

}
}
fclose($file);
$msg="CSV File has been successfully Imported!!";
}   
?>

Wednesday 24 September 2014

Check if the Images already exit or not in the image folder using PHP function

Explaination:

By using PHP function if the Images already exit r not ion the image folder we have to check out using file_exists function r @get_headers.And for backgroung image we have to display in image folder means we have to take anyone has common such as id r name.
Here for example i took id we have to select and fetch with DB and that variable put itin to  the imagepath.


Note:Sometimes file_exists function will not work

Coding:

$url = "images/group_hotel_".trim($ID).".jpg";
$file_headers = @get_headers($url);
if($file_headers[0] == 'Not Found') {
    $banner = "images/group_hotel_nobanner.jpg";
} else {
    $banner = "images/group_hotel_".trim($ID).".jpg";
}


form:

Display the image as in image foldder


<div class="search_bg" style="background-image: url('<?php echo $banner; ?>');">

PHP % Function for displaying image or paragraph in Div to fix as same height

Explaination:

By using this % PHP Function while displaying image or paragraph in dynamically the div height is in different
so we will use the PHP % function to make that has correctly.

Coding:

<?php
$select=mysql_query("select * from tbl ");
$c = 1;-->Intiliaze for % as 1
while($select_hotel12=mysql_fetch_array($select12))
{
.....
.....
?>
<?php 
if($c%3 == 0) {
echo '<div class="clear"></div>';
}
$c++;

} ?>

Note:

     1. In CSS we have to call the calss like .clear{clear:both;}
     
     2. if($c%3 == 0)-->it will dispaly only three columns in the page
       after getting three rows automatically it will form a new line
 
3. $c++-It will incerment the rows

Saturday 20 September 2014

In dropdown the selected values Displayed for Three Selectbox fields Using Ajax


Explaination:

In dropdown the selected values Displayed Using Ajax.In this tutoria i has explained 
the method how we will use ajax in dropdown fields.The field values how we can pass 
to the Ajax Coding and that values we have to retriew from the ajax and how we can 
have the fetch the datas from database.I hope this tutorial we be very usefull for 
the beginners and Developers to develop the coding and get an idea for using the ajax 
in ur Project.
1.First we have to create the form to sent the request to the database.Then we have to use
the onchange function to get the selected values through an ajax.

2.Then we have to Fetch the datas from database what fields we have selected
in dropdown that datas will be displayed in table.For that we have write the coding 
for to create the table and fetch the datas from database.

3.load_data--->Is came from ajax
txtHint2---->Is came from ajax
Because we mentioned this same ajax coding for more than two dropdown means
while loading the datas it is not come correctly so that only we can use the
two different id in ajax.

4.Then we have POST the values through ajax page(ie..serach.php)        
<option value="shipping_"></option>
the option value we have to explode and select the option value we have mentioned in the 
if ,else condition.
5.LIKE function is to be used for to pass the values in ajax.

Create Form for THREE Dropdown by using ONchange events using AJAX:


First we have to create the form to sent the request to the database.Then we have to use

the onchange function to get the selected values through an ajax. 

Froms:
Dropdown1:
<form>
<select name="search"    onchange="showSearchs(this.value)" style="border: 1px solid #97BCFA;"/>
<option value="slam">Search By Booking Number</option>
<?php 
$selects=mysql_query("select * from registered_users WHERE seat_numbers !='' ");
while($cats=mysql_fetch_array($selects))
{
?>
<option value="<?php echo $cats['booking_number'];?>"><?php echo $cats['booking_number'];?></option>
<?php }?>
</select>

Dropdown2:

<select name="search1"    onchange="showSearchs(this.value)" style="border: 1px solid #97BCFA;"/>
<option value="slam">Search By Ticket Delivery</option>
<?php 
$selects=mysql_query("select * from tbl_name ");
while($row=mysql_fetch_array($selects))
{
?>
<option value="delivery_<?php echo $row['did'];?>"><?php echo $row['dname'];?></option>
<?php }?>
</select>

Dropdown3:

<select name="search1"    onchange="showSearchs(this.value)" style="border: 1px solid #97BCFA;"/>
<option value="slam">Search By Shipping Status</option>
<option value="shipping_1">Delivery in progress</option>
<option value="shipping_2">Delivered</option> 
</select>
    </form>

Ajax Script:

<script>
      function showSearchs(str)
            {
            if(str!="")
            {
            var xmlhttp;    
            if (str=="")
              {
              document.getElementById("txtHint2").innerHTML="";
              return;
              }
            if (window.XMLHttpRequest)
              {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
              }
            else
              {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
            xmlhttp.onreadystatechange=function()
              {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                //  if(xmlhttp.responseText!="")
                    //{
             document.getElementById("load_data").innerHTML=xmlhttp.responseText;
                    //}
                }
              }
            xmlhttp.open("GET","search.php?id="+str,true);
            xmlhttp.send();
            }
                }
            </script>


Then we have to Fetch the datas from database what fields we have selected in dropdown that datas will be displayed in table.For that we have write the coding forto create the table and fetch the datas from database.
            
Replace the table using ajax by passing id


 <table width="180%" cellpadding="7" cellspacing="0" border="0" style="margin: 8px 0px 3px;">
            <thead>
            <tr class="table_tr1">
            
                <th>S.No</th>
                 <th>Shipping Status</th>
                <th >payment_status</th>
                 </tr>
          </thead>
          <tbody id="load_data">    
            <?php
            $select=mysql_query("select * from tbl");
             while($row=mysql_fetch_array($sql))
             {
            $id1=$row['id'];
            $status=$row['status'];
            
            ?>
            load_data--->Is came from ajax
            txtHint2---->Is came from ajax
          Because we mentioned this same ajax coding for more than two dropdown means while loading the datas it is not come correctly so that only we can use thetwo different id in ajax.

  <tr  style="text-align:center;" class="table_tr2" id="txtHint2">
                
                        <td><?php  echo $id++;?></td>
                        <td><?php if($row['payment_status'] == "Completed")
 { echo "Confirmed"; } else { echo "Not Confirmed"; } ?></td>
                        <td >
                        <select name="shipping" onchange="showUpdate(this.value,'<?php echo $row['booking_number']; ?>')" style="width: 100px;" id="txtHint3" >
                            <option  <?php if ($row['shipping_status'] == "----" ) echo 'selected'; ?> value="----">----</option>
                            <option  <?php if ($row['shipping_status'] == "Delivery In Progress" ) echo 'selected'; ?> value="Delivery In Progress">Delivery In Progress</option>
                            <option <?php if ($row['shipping_status'] == "Delivered" ) echo 'selected'; ?> value="Delivered">Delivered</option>
                            
                            </select>
                        </td>
                        </tr>

Search.php:

Then we have POST the values through ajax page(ie..serach.php)      
        <option value="shipping_2"></option>
        the option value we have to explode and select the option value we have mentioned in the 
        if ,else condition

<?php
include("db.php");
if($_GET['id'])
{
$id3=$_GET['id'];
$my_data=mysql_real_escape_string($id3);
$i=1;
$sd = explode("delivery_", $my_data);
$shd = explode("shipping_", $my_data);
if($sd[1]) {
$select_data=mysql_query("select  * from registered_users where delivery_option = '$sd[1]' AND seat_numbers != '' ORDER BY id DESC LIMIT 10");
} else if($shd[1]) {

if($shd[1] == "1") {
$sh_option = "Delivery In Progress";
} else {
$sh_option = "Delivered";
}
$select_data=mysql_query("select  * from registered_users where shipping_status = '$sh_option' AND seat_numbers != '' ORDER BY id DESC LIMIT 10");
}else {
$select_data=mysql_query("select  * from registered_users where booking_number LIKE '%$my_data%' OR payment_id LIKE '%$my_data%' OR name LIKE '%$my_data%' OR  email LIKE '%$my_data%' OR  payment_status LIKE '%$my_data%' AND seat_numbers != '' ORDER BY id DESC LIMIT 10");
}
$noofreccord = mysql_num_rows($select_data);
if($noofreccord>0)
{
while($row=mysql_fetch_array($select_data))
{
//$count_data =  count($row);
$id=$row['id'];
echo "<td>" . $row[payment_status]. "</td>";
echo "<td>" . $row[payment_id]. "</td>";
if($row[payment_status] == "Completed") {
echo "<td>Confirmed</td>";
} else {
echo "<td>Not Confirmed</td>";
}
?>
<td>
<select name="shipping" onchange="showUpdate(this.value,'<?php echo $row['booking_number']; ?>')" style="width: 100px;" id="txtHint3" >
<option  <?php if ($row['shipping_status'] == "----" ) echo 'selected'; ?> value="----">----</option>
<option  <?php if ($row['shipping_status'] == "Delivery In Progress" ) echo 'selected'; ?> value="Delivery In Progress">Delivery In Progress</option>
<option <?php if ($row['shipping_status'] == "Delivered" ) echo 'selected'; ?> value="Delivered">Delivered</option>
</select>
</td>
<?php           
echo "</tr>";
}
}
else
{
echo "<tr>";
echo "<td colspan='12' align='center' style='font-weight: bold; padding: 80px 0px 89px; font-size: 20px;color:#3399FF;text-align:center;'>NO DATA FOUND</td>";
echo "</tr>";
}
}
?>

I hope this tutorial is very helpfull for the code developing.In this i mentionedthree dropdown select box for that how to use the ajax and pass the values from ajax page(search.php)and there how we have to request the value and how we can usethis ad fetch from database dispalyed while we selecting the option values the selected details only will displayed.

Thursday 18 September 2014

Display time and date in php

Explaination:

            In this Tutorial to Display time and date in php.While fetching and
            dispalying the time and date ie..in database we'll create the createdon 
            like that some field u created based on when the dates will created we
            want that records so we have to write the coding for that we will use
            strtotime function. 

PHP  Coding:


<?php echo date("j M Y h:i A", strtotime($createdon));?>

date month year time am/pm-->this format it will display
j-->Date,
M-->Month,
Y-->Year,
h:i-->Time,
A-->Year

Status Updation using Ajax and selected value echoed in select box

Explaination:
       Onchange the Select box how to update the Status using PHP we can see in this tutorial.
       In this tutorial we will see by using ajax by onchange the status is to update.We can
       how we can  Passing value through ajax and how we can GET that value through ajax all are 
       explaied in this Turorial.I hope this will helpfull for the Developers and Beginers.
       
Note:
      1.onchange="showUpdate(this.value,'<?php echo $row['db_fieldname']; ?>')"-->we can pass               the value to Ajax
    2.  id="txtHint3"--->We have to replace the value 
    3."GET","shippingstatus_update.php?status="+str+"&id="+id,true---->Like this We have to                pass the values to Ajax page
  4.   $id2=$_GET['id'];---------->Get the values
  5.   $shipping=$_GET['status'];--->Get the values  

Form:    

<td >
<select name="shipping" onchange="showUpdate(this.value,'<?php echo $row['booking_number']; ?>')" style="width: 100px;" id="txtHint3" >
<option  <?php if ($row['shipping_status'] == "----" ) echo 'selected'; ?> value="----">----</option>
<option  <?php if ($row['shipping_status'] == "Delivery In Progress" ) echo 'selected'; ?> value="Delivery In Progress">Delivery In Progress</option>
<option <?php if ($row['shipping_status'] == "Delivered" ) echo 'selected'; ?> value="Delivered">Delivered</option>
</select>
</td>   
 

Ajax Script:

<script>
function showUpdate(str,id)
{
var xmlhttp;    
if (str=="")
{
document.getElementById("txtHint3").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax.php?status="+str+"&id="+id,true);
xmlhttp.send();
}
</script>


Ajax.php:


<?php
include("db.php");
$id2=$_GET['id'];
$shipping=$_GET['status'];
mysql_query("update tbl_name set status='$shipping' where booking_number(db_fieldname)='$id2'");
echo "Status updated Successfully";
?>

Update the Status in the DB as 0 or 1 and echoed the selected value in Select Box Using PHP

Explaination:

            Update the Status in the DB as 0 or 1 and echoed the selected value in Select Box Using PHP. We have to Update the all fields in the tbl u have to use the array for updation.This is the
 easy way and understand the coding for the status Updation. This tutorial is very usefull for the Developers and Beginners.

Note: <?php if($reserved_status['reserved_status'] == '0')
            =>reserved_status-Field in table,
            =>Fetching Variable-$reserved_status,

Form:
    
<select name="status[]">
<option value="0" <?php if($reserved_status['reserved_status'] == '0'){?>selected="selected"<?php }?>>Available to Public</option>
<option value="1" <?php if($reserved_status['reserved_status'] == '1'){?>selected="selected"<?php }?>>Reserved or Blocked </option>      
</select>


Updation coding in PHP:

<?php
if(isset($_POST['update'])) 
    {
        for($i=0;$i<sizeof($_POST['section_id']);$i++) {
        $section_name=$_POST['section_name'][$i];
        $status=$_POST['status'][$i];
        $update=mysql_query("update tbl_name SET  section_name='$section_name',reserved_status='$status' where section_id= '".$_POST[section_id][$i]."' ");
    }
    } 
    
?>

Updation status in Select box the Selected Value Echoed

Explaination:

            In the above code have to update the value in select box.the selected value in the 
            option value in database is to echoed in the select box.In this i have used PHP for 
            to echoed the values.I hope this will very usefull for Developers as well as Begineers.

Form:
         
<td >
<select name="shipping" onchange="showUpdate(this.value,'<?php echo $row['booking_number']; ?>')" style="width: 100px;" id="txtHint3" >
<option  <?php if ($row['shipping_status'] == "----" ) echo 'selected'; ?> value="----">----</option>
<option  <?php if ($row['shipping_status'] == "Delivery In Progress" ) echo 'selected'; ?> value="Delivery In Progress">Delivery In Progress</option>
<option <?php if ($row['shipping_status'] == "Delivered" ) echo 'selected'; ?> value="Delivered">Delivered</option>
</select>
</td>




PHP Coding For Update:

<?php
include("db.php");
$id2=$_GET['id'];//Id is pass through ajax
$shipping=$_GET['status'];//Status is pass through ajax
mysql_query("update tbl_name set shipping_status='$shipping' where booking_number='$id2'");

echo "Status updated Successfully";
?>

Status Update for Delete Option using PHP

Explaination:

            In this coding instead of deleting we have to update the status.
            If the status is 0 means it will display the results and if the status in 
            1 means it has been updated and is not displayed it has hide.In future suppose we want the 
            data means this is the good one to use like this also.
            I hope this tutorial is very helpful for the Developers and the PHP Beginners.

Form:

<form method='post' action=''>
 <input type='hidden' name='reference_number' value='$value3[reference_number]'>
 <input type='submit' name='delete' value='Delete' >
 </form>



Upadte Coding in PHP:




<?php
if(isset($_POST['delete']))
{
//print_r($_POST);exit;
$reference_number=$_POST['reference_number'];
$update=mysql_query("update tbl_name set delete_status='1' where reference_number='$reference_number'");
}
$query3 = "SELECT * FROM tbl_name where delete_status='0' ORDER BY inventory_id desc";
$result3 = mysql_query($query3);
$size   = mysql_num_rows($result3);
while($details = mysql_fetch_array($result3)) {
$row3[] = $details;
}

?>

Fetching with DB:

<?php
if($row3) {
foreach($row3 as $key3 => $value3) {
$slno = $key3 + 1;
$invi = $value3[inventory_id]+123456;
echo "<tr class='table_tr2'>";

echo "<td align='center'>
<form method='post' action=''>
<input type='hidden' name='reference_number' value='$value3[reference_number]'>
<input type='submit' name='delete' value='Delete' class=''>
</form>
</td>";
echo "</tr>";
}
} else {
echo "Not Available";
}

?>     

Update status for all fields using for condition in PHP

Explaination:

             In this above coding we have to update all fields we have to write     for($i=0;$i<sizeof($_POST['tid']);$i++)  for conditions.And we have to update the Status for the fields. 

Form:


<form method="post" name="form">
<td align="center"><?php echo $id;?><input type="hidden" name="tid[]" 
 value="<?php echo $id;?>"/></td>
<td align="center"><input type="text" name="total_bookedseats[]" 
value="<?php echo $total_bookedseats;?>" style="width:120px;"/></td>
</tr>
<?php }?>
<tr align="center"><td align="center" colspan='10'>
<input type="submit" value="Update" name="update" class="signin_butonstyle"/>
</td></tr>
</form>

PHP Update Coding:

<?php
if(isset($_POST['update'])) 
{
for($i=0;$i<sizeof($_POST['tid']);$i++) {
//POST all fields
$total_bookedseats=$_POST['total_bookedseats'][$i];
if($total_noof_seats!=0)
{
$status="Available";
}
else
{
$status="Soldout";
}
$update=mysql_query("update ticket_details SET 
ticket_type='$ticket_type',
unit_price='$unit_price',
service_charge='$service_charge',
total_noof_seats='$total_noof_seats',
total_bookedseats='$total_bookedseats' where tid= '".$_POST[tid][$i]."' ");
}
} 
?>

To display Star images in Database by using PHP

Explaination :
             When we enter the star rating that rate is to insert in database as a number like 1,2,3,...
             that star rating we want to dispaly not in a number we want to doasplay in an image means
             we can use the above coding it a simple way to dispalt star image using php.I hope this 
             tutorial is very usefull the Developers as well as beginners also.

Note : The star images u have to download in google and try this.   

$row['star_rate'];=>star_rate-Database Table field name



Coding In PHP:

<?php
$variable=mysql_query("select  * from tbl_name");
$i = 1;
while ($row = mysql_fetch_array($variable))
{
?>
<td align="left" class="normal">
<?php
if($row['star_rate']==0)
{
?>
<img src="images/star0.jpg" alt="Star Rating" height="16" id="thumb">

<?php } else if($row['star_rate']==1) {?>
<img src="images/star1.jpg" alt="Star Rating" height="16" id="thumb">

<?php } else if($row['star_rate']==2){ ?>
<img src="images/star2.jpg" alt="Star Rating" height="16" id="thumb">

<?php } else if($row['star_rate']==3){ ?>
<img src="images/star3.jpg" alt="Star Rating" height="16" id="thumb">

<?php } else if($row['star_rate']==4){ ?>
<img src="images/star4.jpg" alt="Star Rating" height="16" id="thumb">

<?php } else if($row['star_rate']==5){ ?>
<img src="images/star5.jpg" alt="Star Rating" height="16" id="thumb">

<?php } ?>
</td>

Wednesday 17 September 2014

Generate Captcha using PHP in the Form

Contact us:


Explaination: In this coding i used a simple way for to generate captcha coding using php we no need to use any js and jquery and all.By using this way we can easily understand and it is to very convient for the PHP Developers.For beginners also it has to been very useful and easy to understand.


<div class="container mar-top">
<div class="topic-heading">Contact Us</div>
<form name="form" method="post" action="contact_us.php">
<div class="block-con">
<label class="lbl-con-text">Name<span style="color:red;">*</span></label>
<input type="text"  class="input_text" name="name"  required />

</div>  
<div class="block-con">
<label class="lbl-con-text">Email Id<span style="color:red;">*</span></label>
<input type="email"  class="input_text" name="email" required />
</div>
<div class="block-con">
<label class="lbl-con-text">Mobile Number<span style="color:red;">*</span></label>
<input type="text"  class="input_text" name="zipcode" required />
</div>
<div class="block-con">
<label class="lbl-con-text">City<span style="color:red;">*</span></label>
<input type="text"  class="input_text" name="city" required />
</div>
<div class="block-con">
<label class="lbl-con-text">Message<span style="color:red;">*</span></label>
<textarea class="textarea_text"  name="message" required ></textarea>
</div>
<div class="block-con" style="margin-top:36px">

<label class="lbl-con-text" >Captcha:</label>
<input type="hidden" name="cap1" value="<?php echo $Captcha; ?>" >
<input type="text"  readonly disabled style="width: 9%;background:url(images/pattern-icon.png) repeat-x" value="<?php echo $Captcha; ?>"/>
<input type="text" name="cap2"  style="width:12%;" required />
<span style="color: red; text-align: center; font:bold 14px Arial, Helvetica, sans-serif; margin: 0px 0px 0px 5px;"><?php if($error_message) { echo $error_message; } ?></span>
<p style="color: #474747;font-family: arial;font-size: 11px;font-style: italic;">Please enter the characters displayed in the image into the adjacent input field to complete the process.</p>
</p></div>

<div class="block-con">
<input type="submit" value="Send" name="send" class="con-button" style="margin-top:0px"/>
</div>
</form>
</div>

Captcha coding:

<label class="lbl-con-text" >Captcha:</label>
<input type="hidden" name="cap1" value="<?php echo $Captcha; ?>" >
<input type="text"  readonly disabled style="width: 9%;background:url(images/pattern-icon.png) repeat-x" value="<?php echo $Captcha; ?>"/>
<input type="text" name="cap2"  style="width:12%;" required />
<span style="color: red; text-align: center; font:bold 14px Arial, Helvetica, sans-serif; margin: 0px 0px 0px 5px;"><?php if($error_message) { echo $error_message; } ?></span>
<p style="color: #474747;font-family: arial;font-size: 11px;font-style: italic;">Please enter the characters displayed in the image into the adjacent input field to complete the process.</p>
</p>

PHP Coding:

<?php 
include('connect.php'); 
$Captcha = rand("1111","9999");
if(isset($_POST['send']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$city=$_POST['city'];
$zipcode=$_POST['zipcode'];
$message=$_POST['message'];
if($_POST['cap1'] != $_POST['cap2'])
{
$error_message = "Invalid Captcha";
} else if(!$name || !$email || !$city || !$zipcode || !$message) {
$error_message = "Please enter all details";
}
else {
$insert=mysql_query("insert into contact_us(name,email,city,zipcode,message) values('$name','$email','$city','$zipcode','$message')");
$params1['name'] = $name;
$params1['email'] = $email;
$params1['city'] = $city;
$params1['zipcode'] = $zipcode;
$params1['message'] = $message;

}
}
?>