如何使用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.";
    }
}
?>

评论留言