在本教程中,您將學(xué)習(xí)如何使用PHP和Ajax創(chuàng)建實(shí)時(shí)MySQL數(shù)據(jù)庫搜索功能。
您可以使用Ajax和PHP創(chuàng)建簡單的實(shí)時(shí)數(shù)據(jù)庫搜索功能,當(dāng)您在搜索輸入框中開始鍵入某些字符時(shí),將顯示搜索結(jié)果。
在本教程中,我們將創(chuàng)建一個(gè)實(shí)時(shí)搜索框,該搜索框?qū)⑺阉鱟ountries表并異步顯示結(jié)果。但是,首先我們需要?jiǎng)?chuàng)建該表。
執(zhí)行以下SQL查詢以在MySQL數(shù)據(jù)庫中創(chuàng)建countries表。
CREATE TABLE countries ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL );
創(chuàng)建表后,您需要使用SQL INSERT語句填充一些數(shù)據(jù)。
如果不熟悉創(chuàng)建表的步驟,請查看有關(guān)SQL CREATE TABLE語句的教程,以獲取有關(guān)在MySQL數(shù)據(jù)庫系統(tǒng)中創(chuàng)建表的語法的詳細(xì)信息。
現(xiàn)在,讓我們創(chuàng)建一個(gè)簡單的Web界面,該界面允許用戶實(shí)時(shí)搜索“countries”表中可用的國家/地區(qū)名稱,就像自動(dòng)填充或預(yù)先輸入一樣。
創(chuàng)建一個(gè)名為“ search-form.php”的PHP文件,并將以下代碼放入其中。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP MySQL 數(shù)據(jù)庫實(shí)時(shí)搜索</title>
<style type="text/css">
body{
font-family: Arail, sans-serif;
}
/*設(shè)置搜索框的樣式 */
.search-box{
width: 300px;
position: relative;
display: inline-block;
font-size: 14px;
}
.search-box input[type="text"]{
height: 32px;
padding: 5px 10px;
border: 1px solid #CCCCCC;
font-size: 14px;
}
.result{
position: absolute;
z-index: 999;
top: 100%;
left: 0;
}
.search-box input[type="text"], .result{
width: 100%;
box-sizing: border-box;
}
/* Formatting result items */
.result p{
margin: 0;
padding: 7px 10px;
border: 1px solid #CCCCCC;
border-top: none;
cursor: pointer;
}
.result p:hover{
background: #f2f2f2;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/*更改時(shí)獲取輸入值 */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
//在瀏覽器中顯示返回的數(shù)據(jù)
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
//單擊結(jié)果項(xiàng)時(shí)設(shè)置搜索輸入值
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</html>每次更改搜索輸入的內(nèi)容或在搜索輸入上發(fā)生鍵入事件時(shí),jQuery代碼將Ajax請求發(fā)送至“ backend-search.php”文件,該文件從與國家/地區(qū)相關(guān)的countries表中檢索記錄搜索的字詞。這些記錄稍后將由jQuery插入到<div>并顯示在瀏覽器中。
這是我們的“ backend-search.php”文件的源代碼,該文件根據(jù)Ajax請求發(fā)送的查詢字符串搜索數(shù)據(jù)庫并將結(jié)果發(fā)送回瀏覽器。
<?php
/* 嘗試MySQL服務(wù)器連接。 假設(shè)您正在運(yùn)行MySQL
具有默認(rèn)設(shè)置的服務(wù)器(用戶“ root”,無密碼) */
$link = mysqli_connect("localhost", "root", "", "demo");
//檢查連接
if($link === false){
die("錯(cuò)誤:無法連接。 " . mysqli_connect_error());
}
if(isset($_REQUEST["term"])){
//預(yù)處理select語句
$sql = "SELECT * FROM countries WHERE name LIKE ?";
if($stmt = mysqli_prepare($link, $sql)){
//將變量作為參數(shù)綁定到預(yù)處理語句
mysqli_stmt_bind_param($stmt, "s", $param_term);
//設(shè)置參數(shù)
$param_term = $_REQUEST["term"] . '%';
// Attempt to執(zhí)行預(yù)處理語句
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
//檢查結(jié)果集中的行數(shù)
if(mysqli_num_rows($result) > 0){
//獲取結(jié)果行作為關(guān)聯(lián)數(shù)組
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["name"] . "</p>";
}
} else{
echo "<p>沒有找到匹配的記錄</p>";
}
} else{
echo "錯(cuò)誤:無法執(zhí)行 $sql. " . mysqli_error($link);
}
}
//結(jié)束語句
mysqli_stmt_close($stmt);
}
//關(guān)閉連接
mysqli_close($link);
?><?php
/* 嘗試MySQL服務(wù)器連接。 假設(shè)您正在運(yùn)行MySQL
具有默認(rèn)設(shè)置的服務(wù)器(用戶“ root”,無密碼) */
$mysqli = new mysqli("localhost", "root", "", "demo");
//檢查連接
if($mysqli === false){
die("錯(cuò)誤:無法連接。 " . $mysqli->connect_error);
}
if(isset($_REQUEST["term"])){
//select預(yù)處理語句
$sql = "SELECT * FROM countries WHERE name LIKE ?";
if($stmt = $mysqli->prepare($sql)){
//將變量作為參數(shù)綁定到預(yù)處理語句
$stmt->bind_param("s", $param_term);
//設(shè)置參數(shù)
$param_term = $_REQUEST["term"] . '%';
// 嘗試執(zhí)行預(yù)處理語句
if($stmt->execute()){
$result = $stmt->get_result();
//檢查結(jié)果集中的行數(shù)
if($result->num_rows > 0){
//獲取結(jié)果行作為關(guān)聯(lián)數(shù)組
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<p>" . $row["name"] . "</p>";
}
} else{
echo "<p>沒有找到匹配的記錄</p>";
}
} else{
echo "錯(cuò)誤:無法執(zhí)行 $sql. " . mysqli_error($link);
}
}
//結(jié)束語句
$stmt->close();
}
//關(guān)閉連接
$mysqli->close();
?><?php
/* 嘗試MySQL服務(wù)器連接。 假設(shè)您正在運(yùn)行MySQL
具有默認(rèn)設(shè)置的服務(wù)器(用戶“ root”,無密碼) */
try{
$pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
//將PDO錯(cuò)誤模式設(shè)置為異常
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("錯(cuò)誤:無法連接。 " . $e->getMessage());
}
//嘗試執(zhí)行搜索查詢
try{
if(isset($_REQUEST["term"])){
//創(chuàng)建預(yù)處理語句
$sql = "SELECT * FROM countries WHERE name LIKE :term";
$stmt = $pdo->prepare($sql);
$term = $_REQUEST["term"] . '%';
//綁定參數(shù)到語句
$stmt->bindParam(":term", $term);
//執(zhí)行預(yù)處理語句
$stmt->execute();
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "<p>" . $row["name"] . "</p>";
}
} else{
echo "<p>沒有找到匹配的記錄</p>";
}
}
} catch(PDOException $e){
die("錯(cuò)誤:無法執(zhí)行 $sql. " . $e->getMessage());
}
//結(jié)束語句
unset($stmt);
//關(guān)閉連接
unset($pdo);
?>SQL SELECT語句與LIKE運(yùn)算符結(jié)合使用,以在countries數(shù)據(jù)庫表中查找匹配的記錄。我們實(shí)現(xiàn)了預(yù)處理語句,以提高搜索性能并防止SQL注入攻擊。
注意:在SQL語句中使用用戶輸入之前,請始終對(duì)其進(jìn)行過濾和驗(yàn)證。您還可以使用PHP mysqli_real_escape_string()函數(shù)來轉(zhuǎn)義用戶輸入中的特殊字符,并創(chuàng)建合法的SQL字符串以防止SQL注入。