About PHP - Interaction between AJAX and MySQL

jacklove
Release: 2023-03-25 14:36:01
Original
1883 people have browsed it

AJAX can be used to communicate interactively with the database. It is very important for PHP. This article will explain it.

AJAX database example

The following example will demonstrate how a web page reads information from the database through AJAX:

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

Example

Select a website: Google Taobao Rookie Tutorial Weibo Facebook

Select the corresponding option, the user information will be displayed here...



Instance explanation - MySQL database

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

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  | 菜鸟教程 | http://www.runoob.com/    | 4689  | CN      || 4  | 微博       | http://weibo.com/         | 20    | CN      || 5  | Facebook     | https://www.facebook.com/ | 3     | USA     |+----+--------------+---------------------------+-------+---------+5 rows in set (0.01 sec)
Copy after login

Explanation of examples - HTML page

When the user selects a user in the above drop-down list, the function named "showSite()" will be executed. This function is triggered by the "onchange" event:

test.html File code:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <script>
function showSite(str){
    if (str=="")
    {
        document.getElementById("txtHint").innerHTML="";        return;    } 
    if (window.XMLHttpRequest)
    {
        // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp=new XMLHttpRequest();    }
    else
    {
        // 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","getsite_mysql.php?q="+str,true);    xmlhttp.send();}
</script></head><body>
 <form><select name="users" onchange="showSite(this.value)"><option value="">选择一个网站:</option><option value="1">Google</option><option value="2">淘宝</option><option value="3">菜鸟教程</option><option value="4">微博</option><option value="5">Facebook</option></select></form><br><div id="txtHint"><b>网站信息显示在这里……</b></div>
 </body></html>
Copy after login

showSite() function will perform the following steps:

Check whether a website is selected

Create an XMLHttpRequest object

Create a function that is executed when the server response is ready

Send a request to a file on the server

Please note the parameters added to the end of the URL (q) (Contains the contents of the drop-down list)

PHP file

The server page called through JavaScript in the above paragraph is a PHP file named "getsite_mysql.php". The source code in

"getsite_mysql.php" will run a query against the MySQL database and return the results in an HTML table:

getsite_mysql.php File code:

<?php$q = isset($_GET["q"]) ? intval($_GET["q"]) : &#39;&#39;; 
if(empty($q)) {
    echo &#39;请选择一个网站&#39;;    exit;}
 $con = mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;);if (!$con){
    die(&#39;Could not connect: &#39; . mysqli_error($con));}// 选择数据库mysqli_select_db($con,"test");// 设置编码,防止中文乱码mysqli_set_charset($con, "utf8"); 
$sql="SELECT * FROM Websites WHERE id = &#39;".$q."&#39;"; 
$result = mysqli_query($con,$sql); 
echo "<table border=&#39;1&#39;>
<tr>
<th>ID</th>
<th>网站名</th>
<th>网站 URL</th>
<th>Alexa 排名</th>
<th>国家</th>
</tr>"; 
while($row = mysqli_fetch_array($result)){
    echo "<tr>";    echo "<td>" . $row[&#39;id&#39;] . "</td>";    echo "<td>" . $row[&#39;name&#39;] . "</td>";    echo "<td>" . $row[&#39;url&#39;] . "</td>";    echo "<td>" . $row[&#39;alexa&#39;] . "</td>";    echo "<td>" . $row[&#39;country&#39;] . "</td>";    echo "</tr>";}echo "</table>"; 
mysqli_close($con);?>
Copy after login

Explanation: When a query is sent from JavaScript to a PHP file, what happens is:

PHP opens a connection to the MySQL database

Finds the selected user

Creates the HTML table, Fill in the data and send back the "txtHint" placeholder

This article provides a detailed explanation of the interaction between PHP - AJAX and MySQL. For more learning materials, please pay attention to the php Chinese website.

Related recommendations:

About PHP - The connection between AJAX and PHP

Related knowledge about PHP Simple XML

Related knowledge points about PHP XML DOM

The above is the detailed content of About PHP - Interaction between AJAX and MySQL. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template