Esempio di database MySQL AJAX in PHP
- Pagina precedente XML AJAX
- Pagina successiva responseXML AJAX
AJAX can be used for interactive communication with the database.
AJAX Database Example
In the following AJAX example, we will demonstrate how a web page uses AJAX technology to read information from a MySQL database.
Select a customer from the drop-down list
This application consists of four elements:
- MySQL Database
- A simple HTML form
- JavaScript
- PHP Page
Database
The database used in this example looks something like this:
id | CustomerID | CompanyName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|---|
1 | Alibaba | Alibaba Group | Ma Yun | ...... | Hangzhou | 310002 | Cina |
2 | APPLE | Apple Inc. | Tim Cook | ...... | Cupertino | 95014 | USA |
3 | BAIDU | BAIDU Inc. | Li YanHong | ...... | Beijing | 100080 | Cina |
4 | Canon | Canon USA Inc. | Tsuneji Uchida | ...... | New York | 11042 | USA |
Spiegazione dell'esempio
Nell'esempio sopra, quando l'utente seleziona un cliente dalla lista a discesa, viene eseguita la funzione chiamata "showUser()".
La funzione viene attivata dall'evento onchange.
Questo è il codice HTML:
Esempio
<!doctype html> <html> <head> <script> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) { // codice per IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // codice per IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (this.readyState==4 && this.status==200) { document.getElementById("txtHint").innerHTML=this.responseText; } } xmlhttp.open("GET","/demo/getcustomer.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Scegli un cliente:</option> <option value="1">Alibaba</option> <option value="2">APPLE</option> <option value="3">BAIDU</option> <option value="4">Canon</option> <option value="5">Google</option> <option value="6">HUAWEI</option> <option value="7">Microsoft</option> <option value="8">Nokia</option> <option value="9">SONY</option> <option value="10">Tencent</option> </select> </form> <br> <div id="txtHint"><b>Le informazioni del cliente verranno elencate qui.</b></div> </body> </html>
Spiegazione del codice:
Prima di tutto, controlla se è stato selezionato un cliente. Se non è stato selezionato alcun cliente (str == ""), svuota il contenuto di txtHint ed esci dalla funzione. Se è stato selezionato un cliente, esegui le seguenti operazioni:
- Creare l'oggetto XMLHttpRequest
- Creare la funzione da eseguire quando il server è pronto per rispondere
- Inviare la richiesta al file sul server
- Attenzione, il parametro (q) è aggiunto all'URL (contenuto con elenco a discesa)
File PHP
La pagina sul server chiamata da JavaScript è un file PHP chiamato "getuser.php".
Il codice sorgente di "getuser.php" esegue query sul database MySQL e restituisce i risultati in una tabella HTML:
<?php $q = intval($_GET['q']); $con = mysqli_connect('MyServer','MyUser','MyPassword','Customers'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } $sql="SELECT * FROM customerslist WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table>"; while($row = mysqli_fetch_array($result)) { echo "<tr><th>CustomerID</th><td>" . $row['CustomerID'] . "</td></tr>"; echo "<tr><th>CompanyName</th><td>" . $row['CompanyName'] . "</td></tr>"; echo "<tr><th>ContactName</th><td>" . $row['ContactName'] . "</td></tr>"; echo "<tr><th>Address</th><td>" . $row['Address'] . "</td></tr>"; echo "<tr><th>City</th><td>" . $row['City'] . "</td></tr>"; echo "<tr><th>PostalCode</th><td>" . $row['PostalCode'] . "</td></tr>"; echo "<tr><th>Country</th><td>" . $row['Country'] . "</td></tr>"; } echo "</table>"; mysqli_close($con); ?>
Spiegazione: quando una query viene inviata da JavaScript a un file PHP, si verifica quanto segue:
- PHP apre la connessione con il server MySQL
- Trovato il cliente corretto
- Creare una tabella HTML, riempire i dati e inviare indietro il segnaposto "txtHint"
- Pagina precedente XML AJAX
- Pagina successiva responseXML AJAX