menu



Tuesday 17 March 2020

PHP & AJAX

What is AJAX ?

  • AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
  • Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
  • With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
For complete learning on AJAX, please refer to AJAX Tutorial.

PHP and AJAX Example

To clearly illustrate how easy it is to access information from a database using Ajax and PHP, we are going to build MySQL queries on the fly and display the results on "ajax.html". But before we proceed, lets do ground work. Create a table using the following command.
NOTE − We are assuming you have sufficient privilege to perform following MySQL operations.
CREATE TABLE `ajax_example` (
   `name` varchar(50) NOT NULL,
   `age` int(11) NOT NULL,
   `sex` varchar(1) NOT NULL,
   `wpm` int(11) NOT NULL,
   PRIMARY KEY  (`name`)
) 
Now dump the following data into this table using the following SQL statements.
INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);

Client Side HTML file

Now lets have our client side HTML file which is ajax.html and it will have following code
<html>
   <body>
      
      <script language = "javascript" type = "text/javascript">
         <!--
            //Browser Support Code
            function ajaxFunction(){
               var ajaxRequest;  // The variable that makes Ajax possible!
               
               try {
                  // Opera 8.0+, Firefox, Safari
                  ajaxRequest = new XMLHttpRequest();
               }catch (e) {
                  // Internet Explorer Browsers
                  try {
                     ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                  }catch (e) {
                     try{
                        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                     }catch (e){
                        // Something went wrong
                        alert("Your browser broke!");
                        return false;
                     }
                  }
               }
               
               // Create a function that will receive data 
               // sent from the server and will update
               // div section in the same page.
     
               ajaxRequest.onreadystatechange = function(){
                  if(ajaxRequest.readyState == 4){
                     var ajaxDisplay = document.getElementById('ajaxDiv');
                     ajaxDisplay.innerHTML = ajaxRequest.responseText;
                  }
               }
               
               // Now get the value from user and pass it to
               // server script.
     
               var age = document.getElementById('age').value;
               var wpm = document.getElementById('wpm').value;
               var sex = document.getElementById('sex').value;
               var queryString = "?age=" + age ;
            
               queryString +=  "&wpm=" + wpm + "&sex=" + sex;
               ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
               ajaxRequest.send(null); 
            }
         //-->
      </script>
  
      <form name = 'myForm'>
         Max Age: <input type = 'text' id = 'age' /> <br />
         Max WPM: <input type = 'text' id = 'wpm' />
         <br />
         
         Sex: <select id = 'sex'>
            <option value = "m">m</option>
            <option value = "f">f</option>
         </select>
   
         <input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>
   
      </form>
      
      <div id = 'ajaxDiv'>Your result will display here</div>
   </body>
</html>
NOTE − The way of passing variables in the Query is according to HTTP standard and the have formA.
URL?variable1=value1;&variable2=value2;
Now the above code will give you a screen as given below
NOTE − This is dummy screen and would not work.
Max Age:  

Max WPM: 
Sex:  
Your result will display here

Server Side PHP file

So now your client side script is ready. Now we have to write our server side script which will fetch age, wpm and sex from the database and will send it back to the client. Put the following code into "ajax-example.php" file.
<?php
   
   $dbhost = "localhost";
   $dbuser = "dbusername";
   $dbpass = "dbpassword";
   $dbname = "dbname";
   
   //Connect to MySQL Server
   mysql_connect($dbhost, $dbuser, $dbpass);
   
   //Select Database
   mysql_select_db($dbname) or die(mysql_error());
   
   // Retrieve data from Query String
   $age = $_GET['age'];
   $sex = $_GET['sex'];
   $wpm = $_GET['wpm'];
   
   // Escape User Input to help prevent SQL Injection
   $age = mysql_real_escape_string($age);
   $sex = mysql_real_escape_string($sex);
   $wpm = mysql_real_escape_string($wpm);
   
   //build query
   $query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
   
   if(is_numeric($age))
   $query .= " AND age <= $age";
   
   if(is_numeric($wpm))
   $query .= " AND wpm <= $wpm";
   
   //Execute query
   $qry_result = mysql_query($query) or die(mysql_error());
   
   //Build Result String
   $display_string = "<table>";
   $display_string .= "<tr>";
   $display_string .= "<th>Name</th>";
   $display_string .= "<th>Age</th>";
   $display_string .= "<th>Sex</th>";
   $display_string .= "<th>WPM</th>";
   $display_string .= "</tr>";
   
   // Insert a new row in the table for each person returned
   while($row = mysql_fetch_array($qry_result)) {
      $display_string .= "<tr>";
      $display_string .= "<td>$row[name]</td>";
      $display_string .= "<td>$row[age]</td>";
      $display_string .= "<td>$row[sex]</td>";
      $display_string .= "<td>$row[wpm]</td>";
      $display_string .= "</tr>";
   }
   echo "Query: " . $query . "<br />";
   
   $display_string .= "</table>";
   echo $display_string;
?>
Now try by entering a valid value in "Max Age" or any other box and then click Query MySQL button.
Max Age:  

Max WPM: 
Sex:  
Your result will display here
If you have successfully completed this lesson then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write Ajax applications.

PHP & MySQL

PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database.

What you should already have ?

  • You have gone through MySQL tutorial to understand MySQL Basics.
  • Downloaded and installed a latest version of MySQL.
  • Created database user guest with password guest123.
  • If you have not created a database then you would need root user and its password to create a database.
We have divided this chapter in the following sections −

PHP - Date & Time

Dates are so much part of everyday life that it becomes easy to work with them without thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates easy.

Getting the Time Stamp with time()

PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.
The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.
<?php
   print time();
?>
This will produce the following result −
1480930103
This is something difficult to understand. But PHP offers excellent tools to convert a time stamp into a form that humans are comfortable with.

Converting a Time Stamp with getdate()

The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().
Following table lists the elements contained in the array returned by getdate().
Sr.NoKey & DescriptionExample
1
seconds
Seconds past the minutes (0-59)
20
2
minutes
Minutes past the hour (0 - 59)
29
3
hours
Hours of the day (0 - 23)
22
4
mday
Day of the month (1 - 31)
11
5
wday
Day of the week (0 - 6)
4
6
mon
Month of the year (1 - 12)
7
7
year
Year (4 digits)
1997
8
yday
Day of year ( 0 - 365 )
19
9
weekday
Day of the week
Thursday
10
month
Month of the year
January
11
0
Timestamp
948370048
Now you have complete control over date and time. You can format this date and time in whatever format you wan.

Example

Try out following example
<?php
   $date_array = getdate();
   
   foreach ( $date_array as $key => $val ){
      print "$key = $val<br />";
   }
 
   $formated_date  = "Today's date: ";
   $formated_date .= $date_array['mday'] . "/";
   $formated_date .= $date_array['mon'] . "/";
   $formated_date .= $date_array['year'];
   
   print $formated_date;
?>
This will produce following result −
seconds = 10
minutes = 29
hours = 9
mday = 5
wday = 1
mon = 12
year = 2016
yday = 339
weekday = Monday
month = December
0 = 1480930150
Today's date: 5/12/2016

Converting a Time Stamp with date()

The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.
date(format,timestamp)
The date() optionally accepts a time stamp if omitted then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.
Following table lists the codes that a format string can contain −
Sr.NoFormat & DescriptionExample
1
a
'am' or 'pm' lowercase
pm
2
A
'AM' or 'PM' uppercase
PM
3
d
Day of month, a number with leading zeroes
20
4
D
Day of week (three letters)
Thu
5
F
Month name
January
6
h
Hour (12-hour format - leading zeroes)
12
7
H
Hour (24-hour format - leading zeroes)
22
8
g
Hour (12-hour format - no leading zeroes)
12
9
G
Hour (24-hour format - no leading zeroes)
22
10
i
Minutes ( 0 - 59 )
23
11
j
Day of the month (no leading zeroes
20
12
l (Lower 'L')
Day of the week
Thursday
13
L
Leap year ('1' for yes, '0' for no)
1
14
m
Month of year (number - leading zeroes)
1
15
M
Month of year (three letters)
Jan
16
r
The RFC 2822 formatted date
Thu, 21 Dec 2000 16:01:07 +0200
17
n
Month of year (number - no leading zeroes)
2
18
s
Seconds of hour
20
19
U
Time stamp
948372444
20
y
Year (two digits)
06
21
Y
Year (four digits)
2006
22
z
Day of year (0 - 365)
206
23
Z
Offset in seconds from GMT
+5

Example

Try out following example
<?php
   print date("m/d/y G.i:s<br>", time());
   echo "<br>";
   print "Today is ";
   print date("j of F Y, \a\\t g.i a", time());
?>
This will produce following result −
12/05/16 9:29:47
Today is 5 2016f December 2016 at 9:29 am
Hope you have good understanding on how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in