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 :

Example

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

<html>
<head>
<script type="text/javascript">
function display(strg)
{
if (strg=="")
{
document.getElementById("suggest").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)
{
document.getElementById("suggest").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","AjaxMysqlMain.php?s="+strg,true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b><i>SELECT A BRANCH</i></b></p>
<form>
<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>
</select>
</form>
<br />
<div id="suggest"><b>The Students in the branch is shown here :</b></div>

</body>
</html>

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

<?php
$s=$_GET["s"];

$con = mysql_connect('192.168.10.13', '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'>
<tr>
<th>ID</th>
<th>NAME</th>
<th>GENDER</th>
<th>Branch</th>
</tr>";

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>";

mysql_close($con);
?>

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