Home Php PHP Ajax and Database

 
 

Share on Google+Share on Google+

PHP Ajax and Database

Advertisement
In this following tutorial we will study how to connect PHP, JavaScript, and Database using Ajax.

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);
?>

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 17, 2009

Related Tutorials

Discuss: PHP Ajax and Database  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
ravi
April 28, 2013
php

send me rose india.sql to test this project
DMCA.com