This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Friday 7 June 2013

how to upload many images at once in php

This tutorial tell you how to upload many images at once  in php.

 Just copy the code bellow and save it as "image.php" then open it in your server e.g. localhost.

<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
 {
 $uploaded_images = count($_FILES['file']['name']);

 for ($i = 0; $i < $uploaded_images; $i++)
 {
 if($_FILES["file"]["error"][$i] > 0)
 {
  // if there is error in file uploading
   echo "Return Code: " . $_FILES["file"]["error"][$i] . "<br />";
 }
 else
 {

   // check if file already exit in "images" folder.
   if (file_exists("images/" . $_FILES["file"]["name"][$i]))
   {
    echo $_FILES["file"]["name"][$i] . " already exists. "."<br />";
   }
   else
   { 
    //move_uploaded_file function will upload your image.  if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
    if(move_uploaded_file($_FILES["file"]["tmp_name"][$i], "images/" . $_FILES["file"]["name"][$i]))
    {
     //If you want to stor its name in data base code will go here.
       //file has uploaded successfully, If you want to stor its name in data base. see this link http://b2atutorials.blogspot.com/2012/05/upload-image-into-folder-and-save-its.html
 
     echo $_FILES["file"]["name"][$i] . ' -image uploaded.' .'<br />';
    }
   }
 }
 }
 }
 ?>
<html>
<body>
    <form method="post" enctype="multipart/form-data">
    <input type="file" name="file[]" multiple/>
    <input type="submit" value="submit">
    </form>
</body>
</html>
    

    

how to upload and resize image for thumbnail in php

           

This tutorial tell you how to upload and resize image for thumbnail in php.

Just copy the code bellow and save it as "resize_image.php" then open it in your server e.g. localhost.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
 {
 // By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
 $image = $_FILES["file"]["name"];
 //get the name of the temporary copy of the file stored on the server.
 $uploadedfile = $_FILES['file']['tmp_name'];
 //get the type of the uploaded file.
 $image_type =$_FILES["file"]["type"];
 //imagecreatefrompng — Create a new image from file or URL because we are not sure user inputed file is png or with an other extention therefore we will use if else condition.
 if($image_type=='image/png' || $image_type=='image/x-png')
 {
  $src = imagecreatefrompng($uploadedfile);
 }
 elseif($image_type=='image/gif')
 {
  $src = imagecreatefromgif($uploadedfile);
 }
 elseif($image_type=='image/jpeg' || $image_type=='image/jpg' || $image_type == 'image/pjpeg')
 {
  $src = imagecreatefromjpeg($uploadedfile);
 }
 //getimagesize() this function — Get the size of an image which user inputed. we need orignal size for resizing the image in "imagecopyresampled" function.
 list($width,$height)=getimagesize($uploadedfile);
 //We have get orignal height and width by using list($width,$height)=getimagesize($uploadedfile);
 //Now set your own width and height which you want.
 $new_width=100;
 $new_height=100;
 // Bellow function Create a new true color image so that quality of your image don't change.
 $image_p=imagecreatetruecolor($new_width,$new_height);

 // Turn off alpha blending and set alpha flag // otherwise png's images background color will be black.
    imagealphablending($image_p, false);
    imagesavealpha($image_p, true);
 //Fucntion bellow will resize image
 imagecopyresampled($image_p,$src,0,0,0,0,$new_width,$new_height,$width,$height);

 $filename = "images/". $_FILES['file']['name'];

 if(move_uploaded_file($_FILES["file"]["tmp_name"], $filename))
 {
  if($image_type=='image/png' || $image_type=='image/x-png')
   imagepng($image_p,$filename,9) ;
  else
   imagejpeg($image_p,$filename,100);
  echo 'Image uploaded';
  imagedestroy($image_p);
  //file has uploaded successfully, store its name in data base. see this link http://b2atutorials.blogspot.com/2012/05/upload-image-into-folder-and-save-its.html
 }
 }
?>
<html>
<body>
    <form method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="submit">
    </form>
</body>
</html>
    

 

Tuesday 4 June 2013

how to store data into database easily and reset the form after successful submission

           

Code below will guide you how to store data into database easily. Save this as "save.php" and open it in your host e.g. localhost.
<?php
 session_start();
 // Assing value about your server to these variables for database connection
 $hostname_connect= "localhost";
 $database_connect= "olympic"; //"olympic" this is database name you may create your own database.
 $username_connect= "root";
 $password_connect= "";
 $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
 @mysql_select_db($database_connect) or die (mysql_error());

//if you submit form data submited will be store in database
 if($_POST)
 {
 $key = mt_rand(); // this mt_rand() function genrates randum key for you
 $username = $_POST['username'];
 $email = $_POST['email'];
 $password = $_POST['password'];
 $passconf = $_POST['passconf'];
 $postal_code = $_POST['postal_code'];

 if($_POST['username']=='' || $_POST['email'] =='' || $_POST['password']=='' || $_POST['passconf']=='' || $_POST['postal_code']=='')
 {
  echo "Please fill all fields";
 }
 else
 {
 // save data info database where i have named table as "user" and this is query syntax INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
  $query = "INSERT INTO `user`(`username`,`email`,`password`,`postal_code`,`key`,`status`)VALUES('$username','$email','$password','$postal_code','$key','InActive')";
  $result=mysql_query($query);
   if(!$result)
   {
   echo "Not Saved.";
   }
   else
   {
    //store message in session this will display after redirection.
   $_SESSION["msg"] = "Data has been saved.";
   // line below will redirect you to "save.php" and your form will be reset/refreshed.
   header( "Location: save.php" );
   exit;
   }
 }
 }
 ?>
 <html>
 <body>
<?php
// if session has been set it will show message and unset session.
if(isset($_SESSION["msg"]))
{
 echo '<p style="color:#0C9; font-weight:bold; text-align:center;">'.$_SESSION["msg"].'</p>';
 unset($_SESSION["msg"]);
}
   
 ?>
 <form id='registeration' action='' method='post' >
 <fieldset >
 <legend>Register</legend>
 <label for='username' >Username*: </label><br/>
 <input type='text' name='username' id='username' value="<?php if(!empty($username)) echo $username ?>" maxlength="50" /><br/>
 <label for='email' >Email Address*:</label><br/>
 <input type='text' name='email' id='email' value="<?php if(!empty($email)) echo $email ?>" maxlength="50" /><br/>
 <label for='password' >Password*:</label><br/>
 <input type='password' name='password' id='password' maxlength="50" /><br/>
 <label for='passconf' >Confirm Password*:</label><br/>
 <input type='password' name='passconf' id='password' maxlength="50" /><br/>
 <label for='postal_code' >Postal Code*:</label><br/>
 <input type='text' name='postal_code' id='postal_code' value="<?php if(!empty($postal_code)) echo $postal_code ?>" maxlength="50" /><br/>
 <input type='submit' name='Submit' value='Submit' />
 </fieldset>
 </form>
 </body>
 </html>

 

    

Friday 31 May 2013

how to create your own captcha image easily

This tutorial tell you how to create your own captcha image.
You should follow these steps:
  1. Copy the code below and save it as "create_image.php"
    <?php
    //Start the session so we can store what the security code actually is
    session_start();
    //Send a generated image to the browser
    Create_Captcha_Images();
    exit();
    function Create_Captcha_Images() {
    $width='135';
    $height='30';
    //Let's generate a totally random string using md5
    $md5_hash = md5(rand(0,999));
    //We don't need a 32 character long string so we trim it down to 5
    $code = substr($md5_hash, 15, 5);
    //Set the session to store the security code
    $_SESSION["security_code"] = $code;
    //create image resource using width and height
    $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
    /* set the colours */
    $background_color = imagecolorallocate($image, 255, 255, 255);
    $text_color = imagecolorallocate($image, 0, 0, 0);
    $noise_color = imagecolorallocate($image, 100, 120, 180);
    /* generate random dots in background */
    for( $i=0; $i<110; $i++ ) {
    imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
    }
    /* generate random lines in background */
    for( $i=0; $i<250; $i++ ) {
    imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
    }
    // add white string to box with params: image, font (1-5), x, y, string and color
    imagestring($image, 5, 40, 7, $code, $text_color);
    /* output captcha image to browser */
    header('Content-Type: image/jpeg');
    imagejpeg($image);
    imagedestroy($image);

    }
    ?>
  2. Copy the code below and save it as "contact_us.php".
    <?php
    session_start();
    if(isset($_POST['submit']))
    {
    $image = $_POST['antibot_input_str'];
    if($image == $_SESSION["security_code"])
    {
    echo 'Your Entered code has matched go ahead. e.g. store your form data into database';
    }
    else
    {
    $mail_sent = 'Your Entered code does not match';
    }
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>
    <body>
    <form method="post" action="contact_us.php">
    <table align="center">
    <tr valign="middle">
    <td class="FormButton">First name</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap">
    <input type="text" value="" maxlength="32" size="32" name="firstname" id="firstname">
    </td>
    </tr>
    <tr valign="middle">
    <td class="FormButton">Last name</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap">
    <input type="text" value="" maxlength="32" size="32" name="lastname" id="lastname">
    </td>
    </tr>
    <tr>
    <td class="iv-box-descr" colspan="3">Type the characters you see in the picture. (If you do not see any picture here, please enable images in your web browser options and refresh this page):</td>
    </tr>
    <tr>
    <td class="iv-box" colspan="2">
    <div class="iv-img">
    <img id="imgCaptcha" src="create_image.php"/><br>
    <a onclick="
    document.getElementById('imgCaptcha').src = 'create_image.php?' + Math.random();
    return false;
    " href="javascript:void(0);">Get a different code</a>
    </div>
    <br> </td>
    <td class="iv-box">
    <input type="text" name="antibot_input_str">
    </td>
    </tr>
    <tr valign="middle">
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>
    <input id="insert" name="submit" type="submit" value="Submit" />
    </td>
    </tr>
    </table>
    </form>
    </body>
    </html>

Wednesday 29 May 2013

How to change states list depending on selected country

This tutorial tell you how to How to change states list depending on selected country.
You should follow these steps:
  1. Create your database connection.e.g.
    <?php
    $con=mysql_connect ("localhost","username","password");
    @mysql_select_db('your_bd') or die(mysql_error());
    // Check connection
    if (!$con)
    {
    echo "Failed to connect to MySQL: ";
    }

    ?>
  2. Create states and country tables.
    CREATE TABLE IF NOT EXISTS `states` ( `stateid` int(11) NOT NULL AUTO_INCREMENT, `state` varchar(32) NOT NULL DEFAULT '', `code` varchar(32) NOT NULL DEFAULT '', `country_code` char(2) NOT NULL DEFAULT '', PRIMARY KEY (`stateid`), UNIQUE KEY `code` (`country_code`,`code`), KEY `state` (`state`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=186 ;

    CREATE TABLE IF NOT EXISTS `country` ( `country_code` char(2) NOT NULL default '', `country_name` varchar(90) NOT NULL default '' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  3. Insert values in tables.
    INSERT INTO `country` (`country_code`, `country_name`) VALUES ('GB', 'United Kingdom (Great Britain)'), ('US', 'United States'), ('PK', 'Pakistan');

    INSERT INTO `states` (`stateid`, `state`, `code`, `country_code`) VALUES (1, 'Aberdeenshire', 'ABd', 'GB'), (2, 'Angus', 'AG', 'GB'), (3, 'Argyll', 'ARg', 'GB'), (4, 'Avon', 'AV', 'GB'), (5, 'Ayrshire', 'AY', 'GB'), (6, 'Alabama', 'AL', 'US'), (7, 'Alaska', 'AK', 'US'), (8, 'Arizona', 'AZ', 'US'), (9, 'Arkansas', 'AR', 'US'), (10, 'California', 'CA', 'US');
  4. Copy code below and create a file named "get_state.php"
    <?php
    // Copy this code and create a file named get_state.php
    include_once('db_connection.php');
    $code = $_GET['code'];
    $result = mysql_query("SELECT * FROM `states` WHERE country_code = '".$code."'");
    if(mysql_num_rows($result) > 0)
    {
    echo '<select name="b_state" id="b_state" style="width:220px;">';
    while($row = mysql_fetch_array($result))
    {
    echo "<option value=".$row['code'].">".$row['state']."</option>";
    }
    echo '</select>';
    }
    else
    {
    echo '<input type="text" size="32" value="" name="b_state" id="b_state">';
    }
    ?>
  5. Copy and past code below and save it as "states.php".
    <?php
    // include your database connection.
    include_once('db_connection.php');
    // // create tables
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <!--don't forget to include jquery-->
    <script src="js/jquery.js"></script>
    <script type="text/javascript">
    function change_state(state)
    {
    // Below is post ajax request which goes to "get_state.php" where state list changes on the base of parameter "code" which is set by user on_change event.
    // then result is passed to '#state_container' id of <td> which is parent of <select> element.
    $.post('get_state.php?code='+state, function(data) {
    $('#state_container').html(data);
    });
    }
    </script>
    </head>
    <body>
    <table width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-bottom:5px;">
    <tbody>
    <tr>
    <td></td>
    <td style="padding-top:15px;">
    <form name="registerform" id="insertform" method="post" action="contact_us.php">
    <table width="100%" cellspacing="0" cellpadding="2">
    <tbody>
    <tr valign="middle">
    <td class="FormButton">County/State</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap" id="state_container">

    <?php
    // Below if else condition is for the purpose of saving the users selected value if validation error occur.
    if(isset($_POST['b_country']))
    $code = $_POST['b_country']; //IF contry selected show states of that country else show states of UK.
    else
    $code = 'GB';
    ////// Query below show the states on the base of country_code.
    $result = mysql_query("SELECT * FROM `states` WHERE country_code = '".$code."'");
    if(mysql_num_rows($result) > 0)
    {
    // IF states exit in database show dropdown else show input text field so that user can enter state manually.
    echo '<select name="b_state" id="b_state" style="width:220px;">';
    while($row = mysql_fetch_array($result))
    {
    // Below if condition is for the purpose of saving the users selected value if validation error occur.
    if(isset($_POST['b_state']))
    echo $selected = ($row['code']==$_POST['b_state']) ? "selected='selected'" : "";
    echo "<option ".$selected." value=".$row['code'].">".$row['state']."</option>";
    }
    echo '</select>';
    }
    else
    {
    // Below if else condition is for the purpose of saving the users selected value if validation error occur.
    if(isset($_POST['b_state']))
    $value = $_POST['b_state'];
    else
    $value = '';
    echo '<input type="text" size="32" value="'.$value.'" name="b_state" id="b_state">';
    }
    ?>

    </td>
    </tr>

    <tr valign="middle">
    <td class="FormButton">Country</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap">
    <!-- Below onchange event calls the change_state() with value of selected Country code-->
    <select onchange="javascript: change_state(this.value);" name="b_country" id="b_country" style="width:220px;">
    <?php
    // Query below showes the list of `countries`.
    $result = mysql_query("SELECT * FROM `country`");
    if(mysql_num_rows($result) > 0)
    {
    while($row = mysql_fetch_array($result))
    {
    // Below if else condition is for the purpose of saving the users selected value if validation error occurs.
    if(isset($b_country))
    $selected = ($row['country_code']==$b_country) ? "selected='selected'" : "";
    else // This is for first time uk will be selected by default.
    $selected = ($row['country_code']=='GB') ? "selected='selected'" : "";

    echo "<option ".$selected." value=".$row['country_code'].">".$row['country_name']."</option>";
    }
    }
    ?>
    </select>
    </td>
    </tr>
    </tbody></table>
    </form>
    </body>
    </html>

How to display images stored in database

           

This code is for showing your images from database. (Don't forget to connect with dababase).
You can see storage of images in database here.

<?php
 $query_image = "SELECT * FROM acc_images";
 // This query will show you all images if you want to see only one image pass acc_id='$id' e.g. ""SELECT * FROM acc_images WHERE acc_id='$id'".
 $result = mysql_query($query_image);
 if(mysql_num_rows($result) > 0)
 {
   while($row = mysql_fetch_array($result))
   {
  echo '<img alt="" src="images/'.$row["image"].'">';
   }
 }
 else
 {
  echo 'File name not found in database';
 }
?>

 

Saturday 18 May 2013

Form validation on keyup using jquery (very easy)

           

It is need of some clients that user cannot enter any special character(# @ $ % ^ & *) in text field. E.g. in the place of first name, last name etc. So it is very easy to do so just copy and past the code below and see the fun.

Don't forget to include jquery file. You can download latest jquery file from  this link http://blog.jquery.com/2012/11/13/jquery-1-8-3-released/


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form validation on keyup using jquery very easy (www.b2atutorials.blogspot.com)</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 jQuery('#firstname').keyup(function () {
     this.value = this.value.replace(/[^a-zA-Z]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters.'); return ''; });
  if($(this).val().length > 40)
  {
  alert('Not allowed more than 40 characters');
  $(this).val($(this).val().substring(0, 40));
  }
 });
 jQuery('#lastname').keyup(function () {
     this.value = this.value.replace(/[^a-zA-Z]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters.'); return ''; });
  if($(this).val().length > 40)
  {
  alert('Not allowed more than 40 characters');
  $(this).val($(this).val().substring(0, 40));
  }
 });
 jQuery('#b_address').keyup(function () {
     this.value = this.value.replace(/[^a-zA-Z_0-9 ]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and Numbers.'); return ''; });
  if($(this).val().length > 30)
  {
  alert('Not allowed more than 40 characters');
  $(this).val($(this).val().substring(0, 30));
  }
 });
 jQuery('#b_address_2').keyup(function () {
     this.value = this.value.replace(/[^a-zA-Z_0-9 ]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and Numbers.'); return ''; });
  if($(this).val().length > 30)
  {
  alert('Not allowed more than 40 characters');
  $(this).val($(this).val().substring(0, 30));
  }
 });
 jQuery('#b_zipcode').keyup(function () {
     this.value = this.value.replace(/[^a-zA-Z_0-9 ]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and Numbers.'); return ''; });
  if($(this).val().length > 10)
  {
  alert('Not allowed more than 10 characters');
  $(this).val($(this).val().substring(0, 10));
  }
 });
 jQuery('#b_city').keyup(function () {
     this.value = this.value.replace(/[^a-zA-Z]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters.'); return ''; });
  if($(this).val().length > 40)
  {
  alert('Not allowed more than 40 characters');
  $(this).val($(this).val().substring(0, 40));
  }
 });
 jQuery('#phone').keyup(function () {
     this.value = this.value.replace(/[^0-9]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only Numbers.'); return ''; });
  if($(this).val().length > 20)
  {
  alert('Not allowed more than 20 characters');
  $(this).val($(this).val().substring(0, 20));
  }
 });
 jQuery('#email').keyup(function () {
     this.value = this.value.replace(/[^\w\.+@a-zA-Z_+?\.a-zA-Z\.]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and Numbers.'); return ''; });
  if($(this).val().length > 50)
  {
  alert('Not allowed more than 50 characters');
  $(this).val($(this).val().substring(0, 50));
  }
 });
 jQuery('#subject').keyup(function () {
     this.value = this.value.replace(/[^a-zA-Z_0-9 ]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and Numbers.'); return ''; });
  if($(this).val().length > 30)
  {
  alert('Not allowed more than 40 characters');
  $(this).val($(this).val().substring(0, 30));
  }
 });


});
</script>
</head>
<body>
<table width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-bottom:5px;">
  <tbody><tr>
    <td width="18px"></td>
    <td valign="top"></td>
    <td width="18px"></td>
  </tr>
  <tr>
    <td></td>
    <td style="padding-top:15px;">
<form name="registerform" id="insertform" method="post" action="contact_us.php">
<table width="100%" cellspacing="0" cellpadding="2">
<tbody>
<tr valign="middle">
<td class="FormButton">Title</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<select name="title" id="title">
 <option value="Mr.">Mr.</option>
 <option value="Miss">Miss</option>
 <option value="Mrs.">Mrs.</option>
 <option value="Ms.">Ms.</option>
 <option value="Dr.">Dr.</option>
</select>
</td>
</tr>
<tr valign="middle">
<td class="FormButton">First name</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<input type="text" value="" maxlength="32" size="32" name="firstname" id="firstname">
</td>
</tr>

<tr valign="middle">
<td class="FormButton">Last name</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<input type="text" value="" maxlength="32" size="32" name="lastname" id="lastname">
</td>
</tr>

<tr valign="middle">
<td class="FormButton">Address</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<input type="text" value="" maxlength="64" size="32" name="b_address" id="b_address">
</td>
</tr>

<tr valign="middle">
<td class="FormButton">Address (line 2)</td>
<td></td>
<td nowrap="nowrap">
<input type="text" value="" maxlength="64" size="32" name="b_address_2" id="b_address_2">
</td>
</tr>

<tr valign="middle">
<td class="FormButton">City</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<input type="text" value="" maxlength="64" size="32" name="b_city" id="b_city">
</td>
</tr>

<tr valign="middle">
<td class="FormButton">Zip/Postal code</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<input type="text" onchange="javascript: check_zip_code(document.getElementById('b_country'), this);" value="" maxlength="32" size="32" name="b_zipcode" id="b_zipcode">
</td>
</tr>

<tr valign="middle">
<td class="FormButton">Phone</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<input type="text" value="" maxlength="32" size="32" name="phone" id="phone">
</td>
</tr>

<tr valign="middle">
<td class="FormButton">E-mail</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<input type="text" onchange="javascript: checkEmailAddress(this);" value="" maxlength="128" size="32" name="email" id="email">
</td>
</tr>

<tr valign="middle">
<td class="FormButton">Subject</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<input type="text" value="" maxlength="128" size="32" name="subject" id="subject">
</td>
</tr>
<tr valign="middle">
<td class="FormButton">Message</td>
<td><font class="Star">*</font></td>
<td nowrap="nowrap">
<textarea name="body" rows="12" id="message_body" cols="48"></textarea>
</td>
</tr>
 
 
<tr valign="middle">
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>
<br>
     
<table cellspacing="0" class="SimpleButton"><tbody><tr><td><input id="insert" name="submit" type="submit" value="Submit" /></td></tr></tbody></table>
</td>
</tr>
</tbody></table>
</form>
<br><br></td>
    <td width="18px"></td>
  </tr>
  <tr>
    <td width="18px"></td>
    <td></td>
    <td width="18px"></td>
  </tr>
</tbody></table>
</body>
</html>
    

    

Monday 17 September 2012

csv export and import script using php

Code bellow will be helpfull for you for importing and exporting csv files. Copy the code bellow and save it as "import_export_csv.php" then open it in your host e.g. 'localhost' and start importing, exporting csv files.

<?php
//don't forget to include your database connectivity.
 include('db_connection.php');
 if ($REQUEST_METHOD=="POST" && $_POST['btnSubmit']== 'Export') //this code is for exporting data when you click on "Export" this part of code will be executed.
 {
   // if you want to export data from a database table. You have to give your_table name in bellow query.
   $select = "SELECT * FROM Your_table";
   $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
// code bellow will get names of the fields and set as header of the csv.
   $fields = mysql_num_fields ( $export );
   for ( $i = 0; $i < $fields; $i++ )
   {
    $header .= '"'.mysql_field_name( $export , $i ).'"';
    if($i != $fields-1)
    $header .= ",";
   }
//if data found in database arrange it in csv format and pass to a variable $data.
   while( $row = mysql_fetch_row( $export ) )
   {
    $line = '';
    foreach( $row as $value )
    {                                           
     if ( ( !isset( $value ) ) || ( $value == "" ) )
     {
      $value = '"'."\t".'",';
     }
     else
     {
      $value = str_replace( '"' , '""' , $value );
      $value = '"' . $value . '"' . ",";
     }
     $line .= $value;
    }
 
    $line = substr($line, 0, -1);
    $data .= trim( $line ) . "\n";
   }
   $data = str_replace( "\r" , "" , $data );
//if data=='' not found in database
   if ( $data == "" )
   {
    $data = "\n(0) Records Found!\n";                       
   }
   header("Content-type: application/octet-stream");
   header("Content-Disposition: attachment; filename=products_csv.csv");
   header("Pragma: no-cache");
   header("Expires: 0");
// display fields name and data here
   print "$header\n$data";
   exit;
 }
 elseif ($REQUEST_METHOD=="POST" && $_POST['btnSubmit']== 'Import') //this code is for importing data when you click on "Import" this part of code will be executed.
 {
 
   if ($_FILES[csv][size] > 0)
   {
    //get the csv file
    $file = $_FILES[csv][tmp_name];
    $handle = fopen($file, "r");
    $row=1;
 //fgetcsv — Gets line from file pointer and parse for CSV fields
    while (($line_of_data = fgetcsv($handle, 1000, ",")) !== FALSE)
    {
  //If your first line from csv contains fields names ignore it.
     if($row!=1)
     {
      // $line_of_data is numaric array has your impoted data $line_of_data[0] has your first record from csv which is fields name normaly.
      $query = "insert into yourtable (username, email) values ('$line_of_data[0]', '$line_of_data[1]')";
      mysql_query ($query) or die ( "Sql error : " . mysql_error( ) );
   
     }
      $row++;
        }
    echo "File imported successfuly.";
 
   }
 }
 ?>
 <div style="margin:0 auto; width:100%">
 <form method="post" name="form1" action="import_export_csv.php">
 click here for export a csv file: <input type="submit" name="btnSubmit" value="Export" />
 </form>
 </div>
 <div style="margin:10px auto; width:100%">
 <form method="post" name="form2" enctype="multipart/form-data" action="import_export_csv.php">
 select your .csv file: <input type="file" name="csv" />
 <input type="submit" name="btnSubmit" value="Import" />
 </form>
 </div>    

    

using google map lookup address by postal code

       

   <?php
    // First, we need to take their postcode and get the lat/lng pair:
    $postcode = 'SL1 2PH';
    // Sanitize their postcode:
    $search_code = urlencode($postcode);
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $search_code . '&sensor=false';
 //json_decode() returns an object pass 2nd parameter true to json_decode() if you want to get results as array
    $json = json_decode(file_get_contents($url), true);
 //print_r($json);  uncomment for seeing whole arry
     $lat = $json['results'][0]['geometry']['location']['lat'];
     $lng = $json['results'][0]['geometry']['location']['lng'];
    // Now build the lookup:
    $address_url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lng . '&sensor=false';
 //json_decode() returns an object if you want to get results as array, pass 2nd parameter true e.g. json_decode(file_get_contents($address_url, true))
    $address_json = json_decode(file_get_contents($address_url), true);
    print_r($address_json['results'][0]['formatted_address']);
 ?>    

    

Monday 14 May 2012

How to write a php script for file downloading

In this tutorials you will learn how to write a php script for file downloading.If you want to see how to upload a file into a server click here.

<?php 
// Give the path here where your file is located and make a hyper link like <a href='www.yoursite.com?fname=youpic.jpg'>Download image</a>
//$_GET['fname']; will get the file name you given in hyper link and start downloading

$file = 'admin/upload/'.$_GET['fname'];
header("Expires: 0"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false); 
header("Pragma: no-cache"); 
header("Content-type: application/pdf");   
header('Content-length: '.filesize($file)); 
header('Content-disposition: attachment; filename='.basename($file)); 
readfile($file); 
// Exit script. So that no useless data is output-ed. 
exit; 
?>