Ajax MySql Database

Ajax MySql Database

Posted in : PHP Posted on : January 31, 2011 at 6:27 PM Comments : [ 0 ]

This section contains the example of Ajax using MySql

Ajax MySql Database

This section contains an example in which when you select option(branch) of select dropdown list, It will send the value of selected option(branch) to the server. The server side PHP script handles the request send through xmlhttp object and using the selected value, it query to the MySql database. The records found for the selected branch displays by the PHP script in a table.

The given below example will give you a clear idea :


The JavaScript, Ajax and HTML code of the client side script is given below :

<script type="text/javascript">
function display(strg)
if (strg=="")
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
<p><b><i>SELECT A BRANCH</i></b></p>
<select name="users" onchange="display(this.value)">
<option value="">Select a Branch :</option>
<option value="Computer Science">Computer Science</option>
<option value="Electrical">Electrical</option>
<option value="Electrical & Electronics">Electrical & Electronics</option>
<option value="Information Technology">Information Technology</option>
<option value="MCA">MCA</option>
<option value="Mechanical">Mechanical</option>
<br />
<div id="suggest"><b>The Students in the branch is shown here :</b></div>


The server side PHP script, to handle the Ajax request plus fetching values from database, is given below :


$con = mysql_connect('', 'root', 'root');
if (!$con)
die('Could not connect: ' . mysql_error());

mysql_select_db("ankdb", $con);

$sql="SELECT * FROM studentrecord WHERE branch = '".$s."'";

$result = mysql_query($sql);

echo "<table border='1' bgcolor='yellow'>

while($row = mysql_fetch_array($result))
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['branch'] . "</td>";
echo "</tr>";
echo "</table>";


Output :

Initially it will look like this :

When you select a branch for example-Information Technology, it will display all the records of this branch as :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics