Select data from mysql with PHP and Ajax
Details
- Details
- Category: AJAX
- Created on Friday, 21 September 2012 08:39
- Last Updated on Friday, 21 September 2012 10:11
- Published on Friday, 21 September 2012 08:39
- Written by Administrator
- Hits: 14184
The folowing code select data from mysql database using html and php code with AJAX
file ajax_test.html :
<html>
<head>
<script type="text/javascript">
function showUser(user_id)
{
if (user_id =="")
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+user_id,true);
xmlhttp.send();
}
</script>
</head>
<body>
<b> www.developerpages.gr </b>
<br>
<br>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">FirstName1 Lastname1</option>
<option value="2">FirstName2 Lastname2</option>
<option value="3">FirstName3 Lastname3</option>
<option value="4">FirstName4 Lastname4</option>
</select>
</form>
<br />
<div id="txtHint"><b>User informathions will be listed here.</b></div>
</body>
</html>
File getuser.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '1234');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>username</th>
<th>age</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
and for the MYSQL database use the following sql statements to create database, table and data for this example:
CREATE DATABASE ajax_demo;
USE ajax_demo;
CREATE TABLE user ( id int, FirstName text, LastName text, username text, age int );
INSERT INTO `user` (`id`, `FirstName`, `LastName`, `username`, `Age`) VALUES (1, 'FirstName1', 'Lastname1', 'user1', 35);
INSERT INTO `user` (`id`, `FirstName`, `LastName`, `username`, `Age`) VALUES (2, 'FirstName2', 'Lastname2', 'user2', 37);
INSERT INTO `user` (`id`, `FirstName`, `LastName`, `username`, `Age`) VALUES (3, 'FirstName3', 'Lastname3', 'user3', 40);
INSERT INTO `user` (`id`, `FirstName`, `LastName`, `username`, `Age`) VALUES (4, 'FirstName4', 'Lastname4', 'user4', 45);
Layout :