Sometimes, you need to add live search functionality for populating data without loading the whole page. This tutorial shows you how you can implement Ajax live data search using a PHP mysql database. And you can use the free source code of ajax live data search using jquery php MySQL.
PHP Mysql and jquery Ajax live search from database example. In this tutorial, you will learn how to implement ajax search in PHP and MySQL database.
How to Create Live Search Box Using PHP MySQL and jQuery AJAX
First Create a Database Connection File
Create an ajax search form
Create a PHP Script for Search to DB
1. First Create a Database Connection File
In this step, you will create a file name db.php and update the below code into your file.
The below code is used to create a MySQL database connection in PHP. When we insert form data into MySQL database, there we will include this file:
In this tutorial you’ll learn how to create a live MySQL database search feature using PHP and Ajax.
Ajax Live Database Search
You can create a simple live database search functionality utilizing the Ajax and PHP, where the search results will be displayed as you start typing some character in search input box.
In this tutorial we’re going to create a live search box that will search the countries table and show the results asynchronously. But, first of all we need to create this table.
Step 1: Creating the Database Table
Execute the following SQL query to create the countries table in your MySQL database.
Example
CREATE TABLE countries ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL );
After creating the table, you need to populate it with some data using the SQL INSERT statement. Alternatively, you can download the prepopulated countries table by clicking the download button and import it in your MySQL database.
Please check out the tutorial on SQL CREATE TABLE statement for the detailed information about syntax for creating tables in MySQL database system.
Step 2: Creating the Search Form
Now, let’s create a simple web interface that allows user to live search the names of countries available in our countries table, just like an autocomplete or typeahead.
Create a PHP file named «search-form.php» and put the following code inside of it.
Every time the content of search input is changed or keyup event occur on search input the jQuery code (line no-47 to 67) sent an Ajax request to the «backend-search.php» file which retrieves the records from countries table related to the searched term. Those records later will be inserted inside a by the jQuery and displayed on the browser.
Step 3: Processing Search Query in Backend
And here’s the source code of our «backend-search.php» file which searches the database based on query string sent by the Ajax request and send the results back to browser.
Example
if(isset($_REQUEST["term"])) < // Prepare a select statement $sql = "SELECT * FROM countries WHERE name LIKE ?"; if($stmt = mysqli_prepare($link, $sql))< // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "s", $param_term); // Set parameters $param_term = $_REQUEST["term"] . '%'; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt))< $result = mysqli_stmt_get_result($stmt); // Check number of rows in the result set if(mysqli_num_rows($result) >0)< // Fetch result rows as an associative array while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))< echo "
" . $row["name"] . "
"; > > else< echo "
No matches found
"; > > else < echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); >> // Close statement mysqli_stmt_close($stmt); > // close connection mysqli_close($link); ?>
connect_error); > if(isset($_REQUEST["term"]))< // Prepare a select statement $sql = "SELECT * FROM countries WHERE name LIKE ?"; if($stmt = $mysqli->prepare($sql))< // Bind variables to the prepared statement as parameters $stmt->bind_param("s", $param_term); // Set parameters $param_term = $_REQUEST["term"] . '%'; // Attempt to execute the prepared statement if($stmt->execute())< $result = $stmt->get_result(); // Check number of rows in the result set if($result->num_rows > 0)< // Fetch result rows as an associative array while($row = $result->fetch_array(MYSQLI_ASSOC))< echo "
" . $row["name"] . "
"; > > else< echo "
No matches found
"; > > else < echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); >> // Close statement $stmt->close(); > // Close connection $mysqli->close(); ?>
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); > catch(PDOException $e)< die("ERROR: Could not connect. " . $e->getMessage()); > // Attempt search query execution 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 statement $stmt->bindParam(":term", $term); // execute the prepared statement $stmt->execute(); if($stmt->rowCount() > 0)< while($row = $stmt->fetch())< echo "
" . $row["name"] . "
"; > > else< echo "
No matches found
"; > > > catch(PDOException $e)< die("ERROR: Could not able to execute $sql. " . $e->getMessage()); > // Close statement unset($stmt); // Close connection unset($pdo); ?>
The SQL SELECT statement is used in combination with the LIKE operator (line no-16) to find the matching records in countries database table. We’ve implemented the prepared statement for better search performance as well as to prevent the SQL injection attack.
Note: Always filter and validate user input before using it in a SQL statement. You can also use PHP mysqli_real_escape_string() function to escape special characters in a user input and create a legal SQL string to protect against SQL injection.
PHP: Динамический поиск с использованием PHP, MySQL и AJAX
Иногда нам нужно искать данные, не загружая всю страницу. Из этого туториала Вы узнаете, как реализовать поиск данных в реальном времени с помощью ajax, используя базу данных PHP mysql. Вы можете использовать бесплатный исходный код для поиска данных в реальном времени ajax с помощью jquery php mysql.
Создание динамического поиска с использованием PHP, MySQL и AJAX
Выполните следующие несколько шагов и легко реализуйте динамический поиск из базы данных в реальном времени на PHP, MySQL и jQuery:
1. Создайте файл подключения к базе данных.
На этом этапе вы создадите файл с именем db.php и обновите приведенный ниже код в своем файле.
Приведенный ниже код используется для создания подключения к базе данных MySQL в PHP. Когда мы вставляем данные формы в базу данных MySQL, мы подключаем туда этот файл:
2. Создайте поисковую форму ajax.
На этом этапе вам нужно создать форму поиска ajax и обновить приведенный ниже код в форме поиска.
Search for users
3. Создайте скрипт PHP для поиска в БД.
На этом этапе вам нужно создать одно имя файла ajax-db-search.php и обновить приведенный ниже код в своем файле.
Приведенный ниже код предназначен для поиска в таблице базы данных MySQL с использованием скрипта Ajax PHP:
В этом руководстве вы узнали, как реализовать динамический поиск в реальном времени на PHP с таблицей базы данных MySQL с использованием кода PHP. Это очень простой и легкий пример динамического поиска ajax в базе данных MySQL с использованием PHP.