PHP - AJAX and MySQL


AJAX can be used to communicate with a database interactively.


AJAX Database Example

The following example demonstrates how a web page can read information from a database via AJAX:

SQL file for the Websites table used in this tutorial:websites.sql。

Example


Select an option, and the website information will be displayed here...



Example Explained - MySQL Database

In the above example, the database table we use is shown below:

mysql> select * from websites;
+----+--------------+---------------------------+-------+---------+
| id | name         | url                       | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1  | Google       | https://www.google.cm/    | 1     | USA     |
| 2  | 淘宝       | https://www.taobao.com/   | 13    | CN      |
| 3  | Example | http://www.example.com/    | 4689  | CN      |
| 4  | 微博       | http://weibo.com/         | 20    | CN      |
| 5  | Facebook     | https://www.facebook.com/ | 3     | USA     |
+----+--------------+---------------------------+-------+---------+
5 rows in set (0.01 sec)

Example Explained - HTML Page

When the user selects a website in the dropdown list above, a function called "showSite()" is executed. The function is triggered by the "onchange" event:

test.html file code:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Example (example.com)</title> <script>
function showSite(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) { //IE7+, Firefox, Chrome, Opera, Safari browsers execute code xmlhttp=new XMLHttpRequest(); } else { //IE6, IE5 browsers execute code xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getsite_mysql.php?q="+str,true); xmlhttp.send(); }
</script> </head> <body> <form> <select name="users" onchange="showSite(this.value)"> <option value="">Select a website:</option> <option value="1">Google</option> <option value="2">Taobao</option> <option value="3">Example</option> <option value="4">Weibo</option> <option value="5">Facebook</option> </select> </form> <br> <div id="txtHint"><b>The website information will be displayed here...</b></div> </body> </html>

The showSite() function performs the following steps:

  • Check if a website is selected
  • Create an XMLHttpRequest object
  • Create a function to execute when the server response is ready
  • Send a request to a file on the server
  • Note that a parameter (q) is added to the end of the URL (containing the content of the dropdown list)

PHP File

The server page called via JavaScript above is a PHP file named "getsite_mysql.php".

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

getsite_mysql.php file code:

<?php $q = isset($_GET["q"]) ? intval($_GET["q"]) : ''; if(empty($q)) { echo 'Please select a website'; exit; } $con = mysqli_connect('localhost','root','123456'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //Select database mysqli_select_db($con,"test"); //Set encoding to prevent garbled Chinese characters mysqli_set_charset($con, "utf8"); $sql="SELECT * FROM Websites WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table border='1'> <tr> <th>ID</th> <th>Website Name</th> <th>Website URL</th> <th>Alexa Ranking</th> <th>Country</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['url'] . "</td>"; echo "<td>" . $row['alexa'] . "</td>"; echo "<td>" . $row['country'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?>

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

  1. PHP opens a connection to a MySQL database
  2. Find the selected website
  3. Creates an HTML table, fills it with data, and sends it back to the "txtHint" placeholder
Other Extensions