PHP – AJAX Database Fetcher

The given PHP example explain how a web page can fetch the information from a database with AJAX.

Code Example: Download Example
index.php
<html>
<head>
<script type="text/javascript">
function showUser(str){
  	if(str==""){
		document.getElementById("txtHint").innerHTML="";
		return;
	}

	if(window.XMLHttpRequest){// for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	  }
	else{// for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			document.getElementById("ajax_data").innerHTML=xmlhttp.responseText;
		}
		else{
			document.getElementById("ajax_data").innerHTML="Loading...";
		}
	  }
	xmlhttp.open("GET","db_fetcher.php?q="+str,true);
	xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a product:</option>
<option value="1">Silver</option>
<option value="2">Gold</option>
<option value="3">Platinum</option>
</select>
</form>
<br />
<div id="ajax_data"><b>Person info will be listed here.</b></div>
</body>
</html>
db_fetcher.php
<?php
$q=$_GET["q"];

$conn = mysql_connect('localhost', 'username', 'password') or die ('Could not connect: ' . mysql_error());

mysql_select_db("database_name", $conn);

$sql="SELECT * FROM product WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['name'] . "</td>";
  echo "<td>" . $row['description'] . "</td>";
  echo "<td>" . $row['price'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($conn);
?>

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

Your email address will not be published. Required fields are marked *