ajax example

Searching with PHP and MySQL beyond LIKE

Ever wanted to add a search feature to your php & MySQL driven web site? Then your in luck this tutorial shows you how!

This tutorial assumes you already have a MySQL database and a table with some data already in your table. This tutorial also assumes your familiar with basic php syntax.

You can search your MySQL database in many ways the most common way is using the command LIKE eg. LIKE ‘$search’ which would search for a word like the one you entered into the search field the problem with this is if your search term is not exactly the same as the word your searching for you won’t get a match.

For example if you searched for ‘schoo’ and in your table there was a word called ‘school’ they do not match so you would not get a result.

To get round this you can use a wild card search using the Astrix ‘*’ eg LIKE ‘%$search%’ this would search for any word with all the letters that your search for and then ‘schoo’ would match ‘school’. So that’s exactly what you want to be able to search for part and full words but LIKE has a major drawback you can only search for one word at a time not multiple words!

Thankfully there’s another way of doing your search using a full text search. With a full text search you can search multiple part or full words.

To start open a text editor and define your php page. Then we need to get the search term that was searched for in the event of a search being performed, to do this we use they super global $_GET and assign it to a variable

We then use a php function strip_tags to remove any html, php ,css or any other code from the search term.

We also want to escape the search term before it interacts with the database to prevent a mysql injection attack.

$search = mysql_real_escape_string($search);

Now we have retrieved the search term from the form, we want to make sure its not empty to do this we use an if statement. what this does is if the search term is equal to nothing meaning its empty then echo a message to the user else carry on with the script.

if ($search == "") < echo "

Opps! You forgot to enter a search term.

"; > else

Now all the checks have been done its time to check the search term is in the database using a mysql query. This is like any other mysql query with a select * (all) from the table name where, from this point on its where its different then normal. for the search to work MATCH(articlesTitle) must match the title of the article of what ever field you want to search against the search term AGAINST('$search*' IN BOOLEAN MODE) in boolean mode means true or false mode. In this mode do don't need an index in your database.

(NOTE * With this kind of search you cannot search for 3 characters or less.)

Then a result variable is used to perform the query or show a message if the query fails.

$sql = "SELECT * FROM articles WHERE MATCH(articlesTitle) AGAINST('$search*' IN BOOLEAN MODE)"; $result = mysql_query($sql) or die("Problem, with Query:".mysql_error());

Then were counting how many results were count using the mysql_num_rows function then add the result to a variable.

// Get number of articles, assign value to a variable $count = mysql_num_rows($result);

Now we show the actual results from the search, first were echoing a title and a short message letting the user know what you search for and how many results they were.

echo "

Search Results

"; echo "

you searched for $search there are $count matches.

";

Again were counting the results and creating a new variable with a value of zero.

$TableRows = mysql_num_rows($result); $i = 0;

Then a while loop is performed to show all the results I am not explaining the while loop as this have been explained in Viewing data from a database.

while ($i <$TableRows) < //Add resulting tablerow to relvant variable $articleID = mysql_result($result, $i, "articleID"); $articleTitle = mysql_result($result, $i, "articleTitle"); $articleDesc = mysql_result($result, $i, "articleDesc"); echo "

$articleTitle

"; echo "

$articleDesc

"; echo "

Read More

"; // loop through all results and indent number on each loop $i ++; > // close while loop

A closing bracket is not used to close the else statement to complete the search script.

Now you can search your database show the results and search for part or full words with multiple words.

Opps! You forgot to enter a search term.

"; > else < // perform the search $sql = "SELECT * FROM articles WHERE MATCH(articlesTitle) AGAINST('$search*' IN BOOLEAN MODE)"; $result = mysql_query($sql) or die("Problem, with Query:".mysql_error()); // Get number of articles, assign value to a variable $count = mysql_num_rows($result); echo "

Search Results

"; echo "

you searched for $search there are $count matches.

"; $TableRows = mysql_num_rows($result); $i = 0; while ($i <$TableRows) < //Add resulting tablerow to relvant variable $articleID = mysql_result($result, $i, "articleID"); $articleTitle = mysql_result($result, $i, "articleTitle"); $articleDesc = mysql_result($result, $i, "articleDesc"); echo "

$articleTitle

"; echo "

$articleDesc

"; echo "

Read More

"; // loop through all results and indent number on each loop $i ++; > // close while loop > // close else ?>

Источник

Пишем поиск по сайту на PHP и MySQL

Сегодня мы напишем собственный поиск по сайту с использованием PHP и MySQL. Первым делом рассмотрим краткий алгоритм.

Пользователь выполняет POST запрос из формы поиска, этот запрос передается специальному скрипту-обработчику, который должен обработать поисковый запрос пользователя и возвратить результат.

Сначала скрипт должен обработать должным образом запрос пользователя для обеспечения безопасности, затем выполняется запрос к базе данных, который возвращает в ассоциативном массиве результаты, которые должны будут выводиться на экран. Итак, приступим.

Для начала создадим форму поиска на нужной нам странице:

Эта форма и будет отправлять сам поисковый запрос скрипту search.php. Теперь создадим сам скрипт-обработчик.

 if (!mysql_select_db(DB_NAME)) < exit('Cannot select database'); >mysql_query('SET NAMES utf8'); function search ($query) < $query = trim($query); $query = mysql_real_escape_string($query); $query = htmlspecialchars($query); if (!empty($query)) < if (strlen($query) < 3) < $text = '

Слишком короткий поисковый запрос.

'; > else if (strlen($query) > 128) < $text = '

Слишком длинный поисковый запрос.

'; > else < $q = "SELECT `page_id`, `title`, `desc`, `title_link`, `category`, `uniq_id` FROM `table_name` WHERE `text` LIKE '%$query%' OR `title` LIKE '%$query%' OR `meta_k` LIKE '%$query%' OR `meta_d` LIKE '%$query%'"; $result = mysql_query($q); if (mysql_affected_rows() >0) < $row = mysql_fetch_assoc($result); $num = mysql_num_rows($result); $text = '

По запросу '.$query.' найдено совпадений: '.$num.'

'; do < // Делаем запрос, получающий ссылки на статьи $q1 = "SELECT `link` FROM `table_name` WHERE `uniq_id` = '$row[page_id]'"; $result1 = mysql_query($q1); if (mysql_affected_rows() >0) < $row1 = mysql_fetch_assoc($result1); >$text .= '

href="'.$row1['link'].'/'.$row['category'].'/'.$row['uniq_id'].'" title="'.$row['title_link'].'">'.$row['title'].'

'.$row['desc'].'

'; > while ($row = mysql_fetch_assoc($result)); > else < $text = '

По вашему запросу ничего не найдено.

'; > > > else < $text = '

Задан пустой поисковый запрос.

'; > return $text; > ?>

Естественно, данные таблиц БД нужно задать собственные. Рассмотрим, что делает эта функция. Первые 4 строчки обрабатывают запрос, чтобы он стал безопасным для базы. Такую обработку нужно делать обязательно, т. к. любая форма на Вашем сайте — это потенциальная уязвимость для злоумышленников.

Затем идет проверка, не пустой ли запрос. Если запрос пустой, то возвращаем соответствующее сообщение пользователю. Если запрос не пустой, проверяем его на размер.

Если поисковый запрос имеет длину менее 3 или более 128 символов, также выводим соответствующие сообщения пользователю. Иначе, выполняем запрос к базе данных, который делает выборку идентификатора страницы, ее заголовка, описания, описания ссылки, категорию, если она есть и идентификатор самой статьи, в которой найдены совпадения нужных нам полей с поисковым запросом.

В данном случае мы делаем сравнение с текстом статьи, ее заголовком, ключевыми словами и описанием. Если ничего не найдено, выводим пользователю сообщение об этом. Если запрос возвратил хотя бы одну запись, выполняем в цикле еще один запрос, который делает выборку из таблицы со страницами ссылку на страницу, на которой находится статья.

Если у Вас все статьи на одной странице, вы можете опустить этот шаг. После выполнения запроса при каждой итерации цикла в переменную $text Дозаписываем одну найденную статью.

После завершения цикла, возвращаем переменную $text , Которая и будет выводиться на нашей странице пользователю.

Теперь осталось на этой же странице search.php сделать вызов этой функции и вывести ее результат пользователю.

Также вы можете упростить скрипт поиска по Вашему усмотрению. Желательно создать стиль в таблице css для выводимой информации, чтобы выводимая информация смотрелась более красиво и читабельно. Все замечания вопросы по скрипту можете задавать в комментариях.

Источник

PHP MySQL search database and display results

PHP MySQL search database and display results

Hi friends, in this tutorial you will learn how to perform a PHP MySQL search database and display results in a step-by-step process from scratch. We must know that database searching is very useful in any kind of application or in any dynamic website. Therefore, we can do this with the help of a PHP script and get the desired results based on the search input from HTML forms.

Steps to perform PHP MySQL search database and display results

Step 1:- Create a database in PHP Myadmin as shown in the below screenshot.

PHP MySQL search database and display results

Step 2:- Create a table in the database as shown in the below screenshot.

PHP MySQL search database and display results

Step 3:- Insert data in the table.

In this step, we will insert some data with the help of an SQL query so that we can search from these data and show the results later as shown below

PHP MySQL search database and display results

Query example for inserting data:- INSERT INTO employee_info (id, name, phone_no, age, department, created_at, updated_at) VALUES (NULL, 'ABC', '1234567891', '25', 'IT', current_timestamp(), '0000-00-00 00:00:00.000000');

Now, you can see the inserted data as shown below

PHP MySQL search database and display results

Step 4:- Create a PHP file and Make an HTML form

PHP MySQL search database and display results

In this step, we will create an HTML form with a search element so that we can enter the search input as shown below

Step 5:- Create a PHP file and establish the database connection as shown below

coonnect_test_db.php:-

setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); //echo 'connected'; > catch(PDOException $e) < echo '
'.$e->getMessage(); > ?>

Step 6:- Write a PHP script based on the search input.

prepare("select * from employee_info where department like '%$search%' or name like '%$search%'"); $stmt->execute(); $employee_details = $stmt->fetchAll(PDO::FETCH_ASSOC); > else < $searchErr = "Please enter the information"; >> ?>

Below are the two examples of searching data from the database

  • If the search input is matched with the column value and the column has the single value then it will return the single row as shown in the below screenshot.

PHP MySQL search database and display results

  • If the search input is matched with the column value and the column has more than one value then it will return multiple rows as shown in the below screenshot.

PHP MySQL search database and display results

Complete Code:- phpsearch.php

prepare("select * from employee_info where department like '%$search%' or name like '%$search%'"); $stmt->execute(); $employee_details = $stmt->fetchAll(PDO::FETCH_ASSOC); //print_r($employee_details); > else < $searchErr = "Please enter the information"; >> ?>      .container 


Search Employee Information::
Submit
*


Search Result


# Employee Name Phone No Age Department No data found'; > else< foreach($employee_details as $key=>$value) < ?> > ?>

Download the bootstrap CSS and js files from google and include the path of the files in the href attribute of link tag and src attribute of the script tag respectively.

CONCLUSION:- I hope this article will help you to understand the concept. If you have any doubt then please leave your comment below.

Источник

Читайте также:  Jvm java virtual machine виртуальная машина java
Оцените статью