PHP - AJAX and MySQL

AJAX can be used to communicate interactively with the database.


AJAX database instance

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

html page display

20.png

Explanation of examples - MySQL database

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

01.png

Explanation of examples - HTML page

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

    Title  

数据库信息展示在这

showUser() function will perform the following steps:

· Check whether a user is selected

· Create an XMLHttpRequest object

· Create a function that executes when the server response is ready

· Send a request to a file on the server

· Please note the parameter (q) added to the end of the URL (including the drop-down list Content)


PHP file

The server page called above through JavaScript is a PHP file named "database" .

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

database.php file

  firstname lastname email Age "; while($row = mysqli_fetch_array($result)) { echo ""; echo "" . $row['firstname'] . ""; echo "" . $row['lastname'] . ""; echo "" . $row['email'] . ""; echo "" . $row['Age'] . ""; ; echo ""; } echo ""; mysqli_close($con); ?>

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

1. PHP opens a connection to the MySQL database

2. Found Selected user

3. Create an HTML table, fill in the data, and send back the "txtHint" placeholder

Program results display:

8.png


Continuing Learning
||
Title

数据库信息展示在这
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!