PHP and AJAX MySQL Database Example

AJAX can be used for interactive communication with databases.

AJAX Database Example

In the following AJAX example, we will demonstrate how a web page uses AJAX technology to read information from a MySQL database.

Select a customer from the drop-down list


Customer information will be listed here.

This application consists of four elements:

  • MySQL Database
  • A simple HTML form
  • JavaScript
  • PHP Page

Database

The database used in this example looks something like this:

id CustomerID CompanyName ContactName Address City PostalCode Country
1 Alibaba Alibaba Group Ma Yun ...... Hangzhou 310002 China
2 APPLE Apple Inc. Tim Cook ...... Cupertino 95014 USA
3 BAIDU BAIDU Inc. Li YanHong ...... Beijing 100080 China
4 Canon Canon USA Inc. Tsuneji Uchida ...... New York 11042 USA

Example Explanation

In the above example, when the user selects a customer from the drop-down list above, the function named "showUser()" is executed.

This function is triggered by the onchange event.

This is the HTML code:

Example

<!doctype html>
<html>
<head>
<script>
function showUser(str) {
  if (str=="") {
    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 (this.readyState==4 && this.status==200) {
      document.getElementById("txtHint").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","/demo/getcustomer.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Please select a customer:</option>
<option value="1">Alibaba</option>
<option value="2">APPLE</option>
<option value="3">BAIDU</option>
<option value="4">Canon</option>
<option value="5">Google</option>
<option value="6">HUAWEI</option>
<option value="7">Microsoft</option>
<option value="8">Nokia</option>
<option value="9">SONY</option>
<option value="10">Tencent</option>
</select>
</form>
<br>
<div id="txtHint"><b>Customer information will be listed here.</b></div>
</body>
</html>

Run Instance

Code Explanation:

First, check if a customer has been selected. If no customer has been selected (str == ""), clear the content of txtHint and exit the function. If a customer has been selected, perform the following operations:

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

PHP file

The JavaScript call to the page on the server is a PHP file named "getuser.php".

The source code in "getuser.php" runs queries on the MySQL database and returns the results in an HTML table:

<?php
$q = intval($_GET['q']);
$con = mysqli_connect('MyServer','MyUser','MyPassword','Customers');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM customerslist WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr><th>CustomerID</th><td>" . $row['CustomerID'] . "</td></tr>";
    echo "<tr><th>CompanyName</th><td>" . $row['CompanyName'] . "</td></tr>";
    echo "<tr><th>ContactName</th><td>" . $row['ContactName'] . "</td></tr>";
    echo "<tr><th>Address</th><td>" . $row['Address'] . "</td></tr>";
    echo "<tr><th>City</th><td>" . $row['City'] . "</td></tr>";
    echo "<tr><th>PostalCode</th><td>" . $row['PostalCode'] . "</td></tr>";
    echo "<tr><th>Country</th><td>" . $row['Country'] . "</td></tr>";
}
echo "</table>";
mysqli_close($con);
?>

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

  • PHP opens a connection to the MySQL server
  • Found the correct customer
  • Create an HTML table, fill in the data, and send back the 'txtHint' placeholder