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
Explanation of examples - MySQL database
In the above example, the database table we use is as follows:
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
"; while($row = mysqli_fetch_array($result)) { echo " firstname lastname Age "; echo " "; } echo ""; mysqli_close($con); ?>" . $row['firstname'] . " "; echo "" . $row['lastname'] . " "; echo "" . $row['email'] . " "; echo "" . $row['Age'] . " "; ; echo "
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: