PHP Ajax and Database:
In this following tutorial we will study how to connect PHP, JavaScript, and Database using Ajax.
We will see how to display data about anything from table dynamically. All we have to do is to create a drop down list and select a specific value.
Let's us consider the following:
Database name: roseindia
table name: student
user name : root
password:
Following are the files:
phpAjaxDB.html
<html>
<head>
<script type="text/javascript" src="phpAjaxDB.js"></script>
</head>
<body>
<form>
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="avishek">Avishek</option>
<option value="rahul">Rahul</option>
<option value="vinay">Vinay</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
phpAjaxDB.js
var xmlhttp;
function showUser(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="phpAjaxDB.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
phpAjaxDB.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("roseindia", $con);
$sql="SELECT * FROM student WHERE name = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>name</th>
<th>age</th>
<th>e_id</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['e_id'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>