如何使用PHP、MySQL和AJAX建立即時搜尋框

如何使用PHP、MySQL和AJAX建立即時搜尋框

你有沒有想過,網站是如何在你輸入的同時推薦搜尋詞的?這就是所謂的即時搜尋框。

每次搜尋時,您無需等待整個頁面載入,即時搜尋框會為您提供即時結果。這讓搜尋變得更簡單、更快捷。

即時搜尋框使用 JavaScript (jQuery)、MySQL、PHP 和 AJAX 製作。

在本教程中,我們將向您展示如何使用 PHP、MySQL 和 AJAX 製作即時搜尋框。它們相互配合,使您的搜尋功能充滿活力、反應靈敏。

PHP 處理伺服器端邏輯,MySQL 儲存和檢索資料,而 AJAX 可讓頁面更新搜尋結果,而無需重新載入整個頁面。

為什麼即時搜尋框很重要?

如今,使用者希望一切都快速、簡單。如果他們能在輸入的同時找到結果,就能節省他們的時間,並保持他們對您的內容或產品的興趣。

即時搜尋框能讓遊客更方便快捷地找到他們想要的內容。使用者無需進入不同頁面或等待搜尋載入,而是在輸入的同時獲得即時建議。

即時搜尋框還可以幫助您銷售更多產品,尤其是對於網店而言。透過提供即時結果,它可以引導使用者準確找到他們想要的產品或類別,這樣他們就不必點選太多東西。

即時搜尋框的前提條件

  1. 程式碼編輯器(Sublime 或 Notepad++ 都是不錯的選擇)
  2. Apache 和 MySQL(XAMPP 或 WAMP)。在本文中,我將使用 XAMPP。
  3. HTML、CSS、PHP、MySQL、Javascript、AJAX

首先,我將在電腦上建立指令碼。為此,我需要一個包含一些示例資料的 MySQL 資料庫。然後,我將把它連線到 AJAX 表單。

  • 資料庫主機:localhost
  • 資料庫名稱:autocomplete(或任何你想使用的名稱)
  • 表名:Search
  • 資料庫使用者:root

配置Apache和MySQL

開啟 XAMPP 啟動 Apache 和 MySQL。

啟動 Apache 和 MySQL

現在開啟 URL,localhost:8080/phpmyadmin(8080 是我係統上的埠,你們的可能不同)。點選 New

phpMyadmin

建立一個名為 autocomplete 的資料庫(或任何你喜歡的名稱)。

autocomplete資料庫

複製並貼上以下查詢,建立 Table(search)和列名(ID、Name),然後插入虛擬資料。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
CREATE TABLE search (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(30) NOT NULL
);
INSERT INTO `search` VALUES
(1, 'David Copperfield'),
(2, 'Ricky Ponting'),
(3, 'Cristiano Ronaldo'),
(4, 'Lionel Messi'),
(5, 'Shane Watson');
CREATE TABLE search ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(30) NOT NULL ); INSERT INTO `search` VALUES (1, 'David Copperfield'), (2, 'Ricky Ponting'), (3, 'Cristiano Ronaldo'), (4, 'Lionel Messi'), (5, 'Shane Watson');
CREATE TABLE search (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(30) NOT NULL
);
INSERT INTO `search` VALUES
(1, 'David Copperfield'),
(2, 'Ricky Ponting'),
(3, 'Cristiano Ronaldo'),
(4, 'Lionel Messi'),
(5, 'Shane Watson');

插入虛擬資料

下面是查詢的輸出結果:

資料表建立成功

設定開發環境

要建立搜尋引擎,我們需要在 htdocs 資料夾中建立五個檔案。

  1. 第一個檔案是 Search.php,這是使用者輸入資料和檢視結果的主檔案。
  2. 第二個檔案是 db.php,其中包含資料庫連線的詳細資訊。
  3. 第三個檔案是 Ajax.php,用於向伺服器傳送 AJAX 請求並返回結果。
  4. 第四個檔案是 script.js,其中包含用於執行 AJAX 請求的 JavaScript 函式。
  5. 最後,第五個檔案是 style.css,其中包含搜尋引擎的樣式。

第 1 步:建立主檔案(Search.php)

這是搜尋引擎的主檔案,使用者在此輸入資料並檢視結果。建立一個名為 search.php 的檔案,並在其中貼上以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<title>Live Search using AJAX</title>
<!-- Including jQuery is required. -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!-- Including our scripting file. -->
<script type="text/javascript" src="script.js"></script>
<!-- Including CSS file. -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Search box. -->
<input type="text" id="search" placeholder="Search" />
<br>
<b>Ex: </b><i>David, Ricky, Ronaldo, Messi, Watson, Robot</i>
<br />
<!-- Suggestions will be displayed in below div. -->
<div id="display"></div>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>Live Search using AJAX</title> <!-- Including jQuery is required. --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <!-- Including our scripting file. --> <script type="text/javascript" src="script.js"></script> <!-- Including CSS file. --> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <!-- Search box. --> <input type="text" id="search" placeholder="Search" /> <br> <b>Ex: </b><i>David, Ricky, Ronaldo, Messi, Watson, Robot</i> <br /> <!-- Suggestions will be displayed in below div. --> <div id="display"></div> </body> </html>
<!DOCTYPE html>
<html>
<head>
  <title>Live Search using AJAX</title>
  <!-- Including jQuery is required. -->
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <!-- Including our scripting file. -->
  <script type="text/javascript" src="script.js"></script>
  <!-- Including CSS file. -->
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Search box. -->
  <input type="text" id="search" placeholder="Search" />
  <br>
  <b>Ex: </b><i>David, Ricky, Ronaldo, Messi, Watson, Robot</i>
  <br />
  <!-- Suggestions will be displayed in below div. -->
  <div id="display"></div>
</body>
</html>

第 2 步:建立資料庫連線檔案 (db.php)

該檔案包含資料庫連線的詳細資訊。建立名為 db.php 的檔案並貼上以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
//Database connection.
$con = MySQLi_connect(
"localhost", //Server host name.
"root", //Database username.
"", //Database password.
"autocomplete" //Database name or anything you would like to call it.
);
//Check connection
if (MySQLi_connect_errno()) {
echo "Failed to connect to MySQL: " . MySQLi_connect_error();
}
?>
<?php //Database connection. $con = MySQLi_connect( "localhost", //Server host name. "root", //Database username. "", //Database password. "autocomplete" //Database name or anything you would like to call it. ); //Check connection if (MySQLi_connect_errno()) { echo "Failed to connect to MySQL: " . MySQLi_connect_error(); } ?>
<?php
//Database connection.
$con = MySQLi_connect(
  "localhost", //Server host name.
  "root", //Database username.
  "", //Database password.
  "autocomplete" //Database name or anything you would like to call it.
);
//Check connection
if (MySQLi_connect_errno()) {
  echo "Failed to connect to MySQL: " . MySQLi_connect_error();
}
?>

第 3 步:建立AJAX請求檔案 (Ajax.php)

這是向伺服器傳送 AJAX 請求並返回結果的主要檔案。建立一個名為 ajax.php 的檔案,並在其中貼上以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_POST['search'])) {
//Search box value assigning to $Name variable.
$Name = $_POST['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '%$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
echo '
<ul>
';
//Fetching result from database.
while ($Result = MySQLi_fetch_array($ExecQuery)) {
?>
<!-- Creating unordered list items.
Calling javascript function named as "fill" found in "script.js" file.
By passing fetched result as parameter. -->
<li onclick='fill("<?php echo $Result['Name']; ?>")'>
<a>
<!-- Assigning searched result in "Search box" in "search.php" file. -->
<?php echo $Result['Name']; ?>
</li></a>
<!-- Below php code is just for closing parenthesis. Don't be confused. -->
<?php
}}
?>
</ul>
<?php //Including Database configuration file. include "db.php"; //Getting value of "search" variable from "script.js". if (isset($_POST['search'])) { //Search box value assigning to $Name variable. $Name = $_POST['search']; //Search query. $Query = "SELECT Name FROM search WHERE Name LIKE '%$Name%' LIMIT 5"; //Query execution $ExecQuery = MySQLi_query($con, $Query); //Creating unordered list to display result. echo ' <ul> '; //Fetching result from database. while ($Result = MySQLi_fetch_array($ExecQuery)) { ?> <!-- Creating unordered list items. Calling javascript function named as "fill" found in "script.js" file. By passing fetched result as parameter. --> <li onclick='fill("<?php echo $Result['Name']; ?>")'> <a> <!-- Assigning searched result in "Search box" in "search.php" file. --> <?php echo $Result['Name']; ?> </li></a> <!-- Below php code is just for closing parenthesis. Don't be confused. --> <?php }} ?> </ul>
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_POST['search'])) {
//Search box value assigning to $Name variable.
  $Name = $_POST['search'];
//Search query.
  $Query = "SELECT Name FROM search WHERE Name LIKE '%$Name%' LIMIT 5";
//Query execution
  $ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
  echo '
<ul>
  ';
 //Fetching result from database.
  while ($Result = MySQLi_fetch_array($ExecQuery)) {
      ?>
  <!-- Creating unordered list items.
       Calling javascript function named as "fill" found in "script.js" file.
       By passing fetched result as parameter. -->
  <li onclick='fill("<?php echo $Result['Name']; ?>")'>
  <a>
  <!-- Assigning searched result in "Search box" in "search.php" file. -->
      <?php echo $Result['Name']; ?>
  </li></a>
  <!-- Below php code is just for closing parenthesis. Don't be confused. -->
  <?php
}}
?>
</ul>

第 4 步:建立JavaScript函式檔案 (script.js)

該檔案包含執行 AJAX 請求的 JavaScript 函式。建立名為 scripts.js 的檔案並貼上以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//Getting value from "ajax.php".
function fill(Value) {
//Assigning value to "search" div in "search.php" file.
$('#search').val(Value);
//Hiding "display" div in "search.php" file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "search.php" file. This function will be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "search.php" file.
$("#display").html("");
}
//If name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "Post".
type: "POST",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(html) {
//Assigning result to "display" div in "search.php" file.
$("#display").html(html).show();
}
});
}
});
});
//Getting value from "ajax.php". function fill(Value) { //Assigning value to "search" div in "search.php" file. $('#search').val(Value); //Hiding "display" div in "search.php" file. $('#display').hide(); } $(document).ready(function() { //On pressing a key on "Search box" in "search.php" file. This function will be called. $("#search").keyup(function() { //Assigning search box value to javascript variable named as "name". var name = $('#search').val(); //Validating, if "name" is empty. if (name == "") { //Assigning empty value to "display" div in "search.php" file. $("#display").html(""); } //If name is not empty. else { //AJAX is called. $.ajax({ //AJAX type is "Post". type: "POST", //Data will be sent to "ajax.php". url: "ajax.php", //Data, that will be sent to "ajax.php". data: { //Assigning value of "name" into "search" variable. search: name }, //If result found, this funtion will be called. success: function(html) { //Assigning result to "display" div in "search.php" file. $("#display").html(html).show(); } }); } }); });
//Getting value from "ajax.php".
function fill(Value) {
 //Assigning value to "search" div in "search.php" file.
  $('#search').val(Value);
 //Hiding "display" div in "search.php" file.
  $('#display').hide();
}
$(document).ready(function() {
 //On pressing a key on "Search box" in "search.php" file. This function will be called.
  $("#search").keyup(function() {
     //Assigning search box value to javascript variable named as "name".
      var name = $('#search').val();
     //Validating, if "name" is empty.
      if (name == "") {
         //Assigning empty value to "display" div in "search.php" file.
          $("#display").html("");
      }
     //If name is not empty.
      else {
         //AJAX is called.
          $.ajax({
             //AJAX type is "Post".
              type: "POST",
             //Data will be sent to "ajax.php".
              url: "ajax.php",
             //Data, that will be sent to "ajax.php".
              data: {
                 //Assigning value of "name" into "search" variable.
                  search: name
              },
             //If result found, this funtion will be called.
              success: function(html) {
                 //Assigning result to "display" div in "search.php" file.
                  $("#display").html(html).show();
              }
          });
      }
  });
});

第 5 步:建立樣式檔案(style.css)

該檔案包含搜尋引擎的樣式元素。建立一個名為 style.css 的檔案,並貼上以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
a:hover {
cursor: pointer;
background-color: yellow;
}
a:hover { cursor: pointer; background-color: yellow; }
a:hover {
  cursor: pointer;
  background-color: yellow;
}

測試即時搜尋框

現在可以試用即時搜尋了。為此,請在瀏覽器中輸入以下地址開啟 search.php:localhost:8080/search.php

如何使用PHP、MySQL和AJAX建立即時搜尋框配圖6

然後,按 CTRL+F 鍵,輸入要在資料庫中搜尋的文字。

測試即時搜尋框

當您輸入搜尋時,它會將文字傳送到 script.js 中。然後將請求傳送到 ajax.php。在 ajax.php 中,一個名為 fill() 的函式將把結果傳送回來。該函式還將在 search.php 頁面的 div 中顯示搜尋結果。

小結

當使用者輸入時可以看到搜尋結果,這將使網站更具互動性和活力。即時搜尋框不僅能讓使用者更好地使用網站,還能改善網站的整體執行狀況。

透過使用 jQuery 進行前端 AJAX、PHP 進行伺服器端處理和 MySQL 進行資料庫管理,您可以輕鬆製作出符合現代網站開發標準的搜尋功能。

如果你希望在您的 WordPress 實現即時搜尋支援,可以藉助外掛 SearchWP 來實現

常見問題

問:即時搜尋如何工作?

答:當使用者輸入時,即時搜尋會顯示如何完成關鍵字的建議。可能只需輸入一個字元,方框就會自動完成。

問:為什麼叫即時搜尋?

答:AJAX 搜尋框是搜尋特定資料最方便的方法之一。它也被稱為即時搜尋,因為它會在執行時對使用者的輸入做出反應。

問:為什麼選擇即時搜尋而不是傳統的搜尋框?

答:與傳統搜尋框相比,很多使用者更喜歡即時搜尋,因為它速度快、建議有用。

什麼是 AJAX 即時搜尋?

答:AJAX 即時搜尋是一種在使用者輸入時顯示即時搜尋結果的功能,它使用 AJAX 從伺服器獲取並顯示資料,而無需重新整理頁面。

如何在 PHP 中建立即時搜尋?

答:在 PHP 中建立即時搜尋包括使用 AJAX 將使用者輸入傳送到伺服器端的 PHP 指令碼,然後查詢資料庫以獲得匹配結果並將其傳送回瀏覽器:

建立前端(HTML 和 JavaScript):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<input type="text" id="search" placeholder="Search here...">
<div id="results"></div>
<script>
document.getElementById('search').addEventListener('keyup', function() {
let query = this.value;
if (query !== "") {
fetch('search.php?q=' + query)
.then(response => response.text())
.then(data => document.getElementById('results').innerHTML = data);
} else {
document.getElementById('results').innerHTML = "";
}
});
</script>
<input type="text" id="search" placeholder="Search here..."> <div id="results"></div> <script> document.getElementById('search').addEventListener('keyup', function() { let query = this.value; if (query !== "") { fetch('search.php?q=' + query) .then(response => response.text()) .then(data => document.getElementById('results').innerHTML = data); } else { document.getElementById('results').innerHTML = ""; } }); </script>
<input type="text" id="search" placeholder="Search here...">
<div id="results"></div>
<script>
    document.getElementById('search').addEventListener('keyup', function() {
        let query = this.value;
        if (query !== "") {
            fetch('search.php?q=' + query)
                .then(response => response.text())
                .then(data => document.getElementById('results').innerHTML = data);
        } else {
            document.getElementById('results').innerHTML = "";
        }
    });
</script>

編寫後臺 PHP 指令碼 (search.php)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
if (isset($_GET['q'])) {
$q = $conn->real_escape_string($_GET['q']);
$sql = "SELECT * FROM products WHERE name LIKE '%$q%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<p>" . $row['name'] . "</p>";
}
} else {
echo "No results found.";
}
}
?>
<?php $conn = new mysqli('localhost', 'username', 'password', 'database'); if ($conn->connect_error) { die('Connection failed: ' . $conn->connect_error); } if (isset($_GET['q'])) { $q = $conn->real_escape_string($_GET['q']); $sql = "SELECT * FROM products WHERE name LIKE '%$q%'"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "<p>" . $row['name'] . "</p>"; } } else { echo "No results found."; } } ?>
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}
if (isset($_GET['q'])) {
    $q = $conn->real_escape_string($_GET['q']);
    $sql = "SELECT * FROM products WHERE name LIKE '%$q%'";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "<p>" . $row['name'] . "</p>";
        }
    } else {
        echo "No results found.";
    }
}
?>

評論留言