Ajax PHP MySQL Search Example | Tutsmake.com

PHP 8 AJAX Live Data Search with MySQL Tutorial

PHP 8 AJAX Live search tutorial; In this quick example, we will share with you how to profoundly build a simple live data search in PHP with the help of the MySQL database.

The live data search module is exorbitantly helpful in web and mobile applications; it makes your site visitors life facile by providing them top-notch user experience with utmost profoundness in scanning the content they are looking for.

A search experience has to be immaculate; the high volume of data can easily be searched and scanned through autocomplete search box in php mysql. Ajax live search box shows the desired results to the user based on their searching inputs.

PHP AJAX Live Search with MySQL Database Example

In this PHP jQuery Ajax live search tutorial, we will explain how to create live data search and display search results from the MySQL database.

Читайте также:  Дешифратор шифра цезаря python

Generate Table and Add Test Data in Database

If you do not have a database table ready, use the following SQL query to create a Songs table with id and song_name table properties.

Further, add some data into the Song table to check that data using the jQuery live search box in PHP.

CREATE TABLE Songs ( id int not null, song_name varchar(50) not null); INSERT INTO songs VALUES(1,'Metallica'); INSERT INTO songs VALUES(2,'Megadeth'); INSERT INTO songs VALUES(3,'Anthrax'); INSERT INTO songs VALUES(4,'Eric Clapton'); INSERT INTO songs VALUES(5,'ZZ Top'); INSERT INTO songs VALUES(6,'Van Halen'); INSERT INTO songs VALUES(7,'Lynyrd Skynyrd'); INSERT INTO songs VALUES(8,'ACDC'); INSERT INTO songs VALUES(9,'Black Album'); INSERT INTO songs VALUES(10,'Master of Puppets'); INSERT INTO songs VALUES(11,'Endgame'); INSERT INTO songs VALUES(12,'Peace Sells'); INSERT INTO songs VALUES(13,'The Greater of 2 Evils'); INSERT INTO songs VALUES(14,'Reptile'); INSERT INTO songs VALUES(15,'Greatest Hits');

MySQL Database Connection

Inside your PHP project folder, you need to create a database folder and db.php file within the directory; inside this file, we will make the PHP database connection with the MySQL database.

Add the following db connection code in database/db.php file:

 $servername = 'localhost'; $username = 'root'; $password = ''; $dbname = "php_db"; $connection = mysqli_connect($servername, $username, $password, $dbname); // Check connection if(!$connection) die('Database connection error : ' .mysql_error()); > ?>

MySQL Live Search Query

Inside your project directory, you have to create the ajax-live-search.php file; we will import the database connection within this file.

Additionally, create the query to fetch all the data from the Songs table and print it on the view. If the result doesnt found, then show the alert message to the user that data not found.

Update the ajax-live-search.php file:

 require_once "./database/db.php"; if (isset($_POST['query']))  $query = "SELECT * FROM Songs WHERE song_name LIKE '$_POST['query']>%' LIMIT 100"; $result = mysqli_query($connection, $query); if (mysqli_num_rows($result) > 0)  while ($res = mysqli_fetch_array($result))  echo $res['song_name']. "
"
; > > else echo "
Song not found
"
; > > ?>

Create Ajax Live Database Search in PHP

In the final step, we have to implement the live search eventually. We will use the Bootstrap UI for styling the search component and also import the jQuery through CDN. Use the AJAX to make the POST request to fetch the data from the database.

Create the index file, and update the below code in the index.php file.

!DOCTYPE html> html> head> title>Ajax PHP MySQL Live Search Example/title> link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"> /head> body> div class="container mt-5" style="max-width: 555px"> div class="card-header alert alert-warning text-center mb-3"> h2>PHP MySQL Live Search/h2> /div> input type="text" class="form-control" name="live_search" id="live_search" autocomplete="off" placeholder="Search . "> div id="search_result">/div> /div> script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">/script> script type="text/javascript"> $(document).ready(function ()  $("#live_search").keyup(function ()  var query = $(this).val(); if (query != "")  $.ajax( url: 'ajax-live-search.php', method: 'POST', data:  query: query >, success: function (data)  $('#search_result').html(data); $('#search_result').css('display', 'block'); $("#live_search").focusout(function ()  $('#search_result').css('display', 'none'); >); $("#live_search").focusin(function ()  $('#search_result').css('display', 'block'); >); > >); > else  $('#search_result').css('display', 'none'); > >); >); /script> /body> /html>

PHP AJAX Live Data Search

Conclusion

Throughout this PHP MySQL example, we described how to create live data search in PHP using AJAX quickly; we also shared how to retrieve data from the MySQL database and display data results in live search.

We believe you liked this basic tutorial and will share it with others.

positronX.io - Tamso Ma Jyotirgamaya

A Full-stack developer with a passion to solve real world problems through functional programming.

Источник

Ajax Live Data Search using jQuery PHP MySQL

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:

2. Create an ajax search form

In this step, you need to create an ajax search form and update the below code into your ajax search form.

      
Search for users

3. Create a PHP Script for Search to DB

In this step, you need to create one file name ajax-db-search.php and update the below code into your file.

The below code is to search into a MySQL database table using an Ajax PHP script:

%' LIMIT 100"; $result = mysqli_query($conn, $query); if (mysqli_num_rows($result) > 0) < while ($user = mysqli_fetch_array($result)) < echo $user['name']."
"; > > else < echo "

User not found.

"; > > ?>

Conclusion

In this tutorial, you have learned how to implement live search in PHP with MySQL database table using PHP code.

This is a very basic and easy example of ajax search into the MySQL database using PHP code.

Источник

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:

%' LIMIT 100"; $result = mysqli_query($conn, $query); if (mysqli_num_rows($result) > 0) < while ($user = mysqli_fetch_array($result)) < echo $user['name']."
"; > > else < echo "

User not found.

"; > > ?>

В этом руководстве вы узнали, как реализовать динамический поиск в реальном времени на PHP с таблицей базы данных MySQL с использованием кода PHP. Это очень простой и легкий пример динамического поиска ajax в базе данных MySQL с использованием PHP.

Источник

Быстрый поиск с выводом результатов

Виджет на JQuery и AJAX, который покажет результаты поиска непосредственно при вводе в текстовое поле.

Форма

В обычную форму поиска добавляется пустой .

JQuery скрипт получает введенный в поле текст и отправляет его POST-запросом на обработчик /ajax_search.php , ответ выводится в всплывающей плашке.

$(document).ready(function() < var $result = $('#search_box-result'); $('#search').on('keyup', function()< var search = $(this).val(); if ((search != '') && (search.length >1))< $.ajax(< type: "POST", url: "/ajax_search.php", data: , success: function(msg) < $result.html(msg); if(msg != '')< $result.fadeIn(); >else < $result.fadeOut(100); >> >); > else < $result.html(''); $result.fadeOut(100); >>); $(document).on('click', function(e) < if (!$(e.target).closest('.search_box').length)< $result.html(''); $result.fadeOut(100); >>); $(document).on('click', '.search_result-name a', function()< $('#search').val($(this).text()); $result.fadeOut(100); return false; >); $(document).on('click', function(e) < if (!$(e.target).closest('.search_box').length)< $result.html(''); $result.fadeOut(100); >>); >);

Стили формы поиска и результатов:

.search_box < position: relative; >.search_box input[type="text"] < display: block; width: 100%; height: 35px; line-height: 35px; padding: 0; margin: 0; border: 1px solid #fd4836; outline: none; overflow: hidden; border-radius: 4px; background-color: rgb(255, 255, 255); text-indent: 15px; font-size: 14px; color: #222; >.search_box input[type="submit"] < display: inline-block; width: 17px; height: 17px; padding: 0; margin: 0; border: 0; outline: 0; overflow: hidden; text-indent: -999px; background: url(https://snipp.ru/demo/127/search.png) 0 0 no-repeat; position: absolute; top: 9px; right: 16px; >/* Стили для плашки с результатами */ .search_result

Источник

Оцените статью