PHP - AJAX 與 MySQL
AJAX 可用於與資料庫進行互動式通訊。
AJAX 資料庫實例
#下面的實例將示範網頁如何透過AJAX 從資料庫讀取資訊:
實例
<html> <head> <script> function showUser(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","getuser.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Glenn Quagmire</option> <option value="4">Joseph Swanson</option> </select> </form> <br> <div id="txtHint"><b>Person info will be listed here.</b></div> </body> </html>showUser() 函數會執行以下步驟:· 檢查是否有使用者被選擇· #
#· 建立伺服器回應的內容)
PHP 檔案上面這段透過JavaScript 呼叫的伺服器頁面是名為"getuser.php" 的PHP 檔案。
"getuser.php" 中的原始程式碼會執行一次針對MySQL 資料庫的查詢,然後在HTML 表格中傳回結果:
<?php $q=$_GET["q"]; $con = mysqli_connect('localhost','peter','abc123','my_db'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"ajax_demo"); $sql="SELECT * FROM user WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Hometown'] . "</td>"; echo "<td>" . $row['Job'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?>解釋:當查詢從JavaScript 傳送到PHP 檔案時,將發生:
1. PHP 開啟一個到MySQL 資料庫的連接
2. 找到已選取的使用者
#建立HTML 表格,填入數據,並傳回"txtHint " 佔位符
#下一節