Easy Tutorial
❮ Func Ftp Alloc Php Ref Date ❯

PHP - AJAX with MySQL


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 using AJAX:

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

Example


Example Explanation - MySQL Database

In the example above, the database table we used is as follows:

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

Example Explanation - HTML Page

When a user selects a user from the dropdown list above, the function "showSite()" is executed. This function is triggered by the "onchange" event:

test.html File Code:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>tutorialpro.org(tutorialpro.org)</title> 
<script>function showSite(str)
{
    if (str=="")
    {
        document.getElementById("txtHint").innerHTML="";
        return;
    } 
    if (window.XMLHttpRequest)
    {
        // IE7+, Firefox, Chrome, Opera, Safari execute code
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // IE6, IE5 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">tutorialpro.org</option>
<option value="4">Weibo</option>
<option value="5">Facebook</option>
</select>
</form>
<br>
<div id="txtHint"><b>Website information will be displayed here...</b></div>

</body>
</html>

The showSite() function will perform the following steps:


PHP File

The server page called by the 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 results 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 Chinese乱码
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 Rank</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 will happen:

❮ Func Ftp Alloc Php Ref Date ❯