English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to create a real-time MySQL database search feature using PHP and Ajax.
You can create a simple real-time database search feature using Ajax and PHP, which will display search results as you start typing characters in the search input box.
In this tutorial, we will create a real-time search box that searches the 'countries' table and displays the results asynchronously. However, first we need to create the table.
Execute the following SQL query to create the 'countries' table in the MySQL database.
CREATE TABLE countries ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL );
After creating the table, you need to useSQL INSERT statementfill in some data.
If you are not familiar with the steps to create a table, please seeSQL CREATE TABLE statementtutorial to get detailed information about the syntax for creating tables in the MySQL database system.
Now, let's create a simple web interface that allows users to search for "countries" in real time"available in the tablecountry/regionname, as if it were auto-completion or pre-input.
Create a named " search-put the following code into the PHP file "form.php".
<!DOCTYPE html> <html> <head> <meta charset="UTF-8> <title>PHP MySQL database real-time search</title> <style type="text/css"> body{ font-family: Arail, sans-serif; } /*Set the style of the search box */ .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-1jquery12jquery4./script> .min.js"></<script type="text javascript"> $(document).ready(function(){-$('.search /*box input[type="text"]').on("keyup input", function(){ */ Change to get the input value var inputVal = $(this).val(); var resultDropdown = $(this).siblings(".result"); if(inputVal.length){-$.get("search.php", {term: inputVal}).done(function(data){ //Display the returned data in the browser resultDropdown.html(data); }); } else{ resultDropdown.empty(); } }); //Set the search input value when clicking on the result item $(document).on("click", ".result p", function(){ $(this).parents(".search-$(this).parent(".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>
Every time the content of the search input is changed or a key press event occurs in the search input, the jQuery code sends an Ajax request to the 'backend'-the 'search.php' file, which retrieves data fromcountry/regionrelatedcountriesSearch for the words in the table records. These records will later be inserted into<div>and displays them in the browser.
This is our 'backend'-source code of the 'search.php' file, which searches the database based on the query string sent by Ajax requests and sends the results back to the browser.
<?php /* try to connect to MySQL server. Assume you are running MySQL server with default settings (user "root", no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); //Check the connection if($link === false){ die("Error: Unable to connect. " . mysqli_connect_error()); } if(isset($_REQUEST["term"])){ //Prepare the select statement $sql = "SELECT * FROM countries WHERE name LIKE ?"; if($stmt = mysqli_prepare($link, $sql)){ //Bind the variable as a parameter to the prepared statement mysqli_stmt_bind_param($stmt, "s", $param_term); //Set the parameter $param_term = $_REQUEST["term"] . '%'; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ $result = mysqli_stmt_get_result($stmt); //Check the number of rows in the result set if(mysqli_num_rows($result) > 0){ //Get the result row as an associative array while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ echo "<p>" . $row["name"] . "</p>"; } } else{ echo "<p>no matching records found</p>"; } } else{ echo "Error: Unable to execute $sql." . mysqli_error($link); } } //end statement mysqli_stmt_close($stmt); } //close the connection mysqli_close($link); ?>
<?php /* try to connect to MySQL server. Assume you are running MySQL server with default settings (user "root", no password) */ $mysqli = new mysqli("localhost", "root", "", "demo"); //Check the connection if($mysqli === false){ die("Error: Unable to connect. " . $mysqli->connect_error); } if(isset($_REQUEST["term"])){ //Select prepared statement $sql = "SELECT * FROM countries WHERE name LIKE ?"; if($stmt = $mysqli->prepare($sql)){ //Bind the variable as a parameter to the prepared statement $stmt->bind_param("s", $param_term); //Set the parameter $param_term = $_REQUEST["term"] . '%'; // Attempt to execute the prepared statement if($stmt->execute()){ $result = $stmt->get_result(); //Check the number of rows in the result set if($result->num_rows > 0){ //Get the result row as an associative array while($row = $result-fetch_array(MYSQLI_ASSOC)){ echo "<p>" . $row["name"] . "</p>"; } } else{ echo "<p>no matching records found</p>"; } } else{ echo "Error: Unable to execute $sql." . mysqli_error($link); } } //end statement $stmt->close(); } //close the connection $mysqli->close(); ?>
<?php /* try to connect to MySQL server. Assume you are running MySQL server with default settings (user "root", no password) */ try{ $pdo = new PDO("mysql:host=localhost;dbname=demo", "root", ""); //set PDO error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ die("Error: Unable to connect. ". $e->getMessage()); } //try to execute search query try{ if(isset($_REQUEST["term"])){ //create prepared statement $sql = "SELECT * FROM countries WHERE name LIKE :term"; $stmt = $pdo->prepare($sql); $term = $_REQUEST["term"] . '%'; //bind parameters to the statement $stmt->bindParam(":term", $term); //execute prepared statement $stmt->execute(); if($stmt->rowCount() > 0){ while($row = $stmt->fetch()){ echo "<p>" . $row["name"] . "</p>"; } } else{ echo "<p>no matching records found</p>"; } } } catch(PDOException $e){ die("Error: Unable to execute $sql. ". $e->getMessage()); } //end statement unset($stmt); //close the connection unset($pdo); ?>
SQL SELECTstatements withLIKEoperators to be used together incountriesto find matching records in the database table. We have implementedprepared statements,to improve search performance and preventSQL injectionattack.
Note:Always filter and validate user input before using it in SQL statements. You can also use the PHP mysqli_real_escape_string() function to escape special characters in user input and create a valid SQL string to prevent SQL injection.