# PHP - AJAX and MySQL

« Previous
Next Chapter »

AJAX can be used for interactive communication with a database.

## AJAX Database Example

The following example will demonstrate how a web page can fetch information from a database with AJAX:

## Example

Person info will be listed here...

## Example Explained - The MySQL Database

The database table we use in the example above looks like this:

id | FirstName | LastName | Age | Hometown | Job
--- | --- | --- | --- | --- | ---
1 | Peter | Griffin | 41 | Quahog | Brewery
2 | Lois | Griffin | 40 | Newport | Piano Teacher
3 | Joseph | Swanson | 39 | Quahog | Police Officer
4 | Glenn | Quagmire | 41 | Quahog | Pilot

## Example Explained

In the example above, when a user selects a person in the dropdown list above, a function called "showUser()" is executed.

The function is triggered by the onchange event.

Here is the HTML code:

## Example

<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
Run example »

Code explanation:

First, check if no person is selected (str == ""). If no person is selected, clear the content of the txtHint placeholder and exit the function.

If a person is selected, do the following:

- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send the request off to a file on the server
- Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

## The PHP File

The page on the server called by the JavaScript above is a PHP file called "getuser.php".

The source code in "getuser.php" runs a query against a MySQL database, and returns the result in an HTML table:

<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:

1. PHP opens a connection to a MySQL server
2. The correct person is found
3. An HTML table is created, filled with data, and sent back to the "txtHint" placeholder

« Previous
Next Chapter »

### WEB HOSTING

UK Reseller Hosting

### WEB BUILDING

FREE Website BUILDER Free HTML5 Templates

### W3SCHOOLS EXAMS

HTML, CSS, JavaScript, PHP, jQuery, XML, and ASP Certifications

### SHARE THIS PAGE

### Color Picker

### HTML/CSS

HTML Tutorial HTML5 Tutorial CSS Tutorial CSS3 Tutorial Bootstrap Tutorial

### JavaScript

JavaScript Tutorial jQuery Tutorial jQuery Mobile Tutorial AngularJS Tutorial AJAX Tutorial JSON Tutorial

### Graphics

Canvas Tutorial SVG Tutorial Google Maps Tutorial

### Server Side

SQL Tutorial PHP Tutorial ASP Tutorial ASP.NET Tutorial VBScript Tutorial AppML Tutorial

### Web

Web Building Web Statistics Web Certification

### XML

XML Tutorial DTD Tutorial Schema Tutorial XML DOM Tutorial XPath Tutorial XSLT Tutorial XQuery Tutorial XSL-FO Tutorial RSS Tutorial WSDL Tutorial

### HTML/CSS

HTML Tag Reference HTML Event Reference HTML Color Reference CSS 1,2,3 Reference Bootstrap Reference

### JavaScript

JavaScript Reference HTML DOM Reference jQuery Reference jQuery Mobile Reference Google Maps Reference

### Server Side

PHP Reference SQL Reference ASP Reference VBScript Reference Razor Reference ASP.NET Reference

### XML

XML DOM Reference XSLT Reference XSL-FO Reference XPath Reference XQuery Reference Schema Reference RSS Reference SVG Reference

### HTML Charsets

HTML Character Sets HTML ASCII HTML ANSI HTML Windows-1252 HTML ISO-8859-1 HTML Symbols HTML UTF-8

### HTML/CSS

HTML Examples CSS Examples

### Browser Scripting

JavaScript Examples HTML DOM Examples jQuery Examples jQuery Mobile Examples AngularJS Examples AJAX Examples

### Server Scripting

PHP Examples ASP Examples VBScript Examples Razor Examples .NET Examples

### XML Languages

XML Examples DTD Examples XML DOM Examples XSL Examples XSLT Examples XPath Examples XQuery Examples Schema Examples RSS Examples SVG Examples