Keyword Search with PHP PDO and MySQL

Keyword search using SQL

A keyword-search form usually needs two separate jobs: convert visitor text into search terms, then execute a safe SQL query. The SQL should never be built by concatenating raw visitor input directly into the statement.

For an autocomplete implementation using a database source, see Autocomplete Search.

Demo of Keyword Search

This example uses PHP trim functions, string splitting, loops and PDO. For result presentation, see displaying MySQL data and pagination.

Normalize the search text

$searchText = trim($searchText);

Split multiple keywords

$keywords = preg_split('/\s+/', $searchText, -1, PREG_SPLIT_NO_EMPTY);

The loop replaces the old removed each() pattern with foreach; see the PHP condition, substring, and string length tutorials for the related operations.

Build LIKE conditions and parameters

$conditions = [];
$params = [];
foreach ($keywords as $i => $word) {
    $name = ':kw' . $i;
    $conditions[] = 'name LIKE ' . $name;
    $params[$name] = '%' . $word . '%';
}
$sql = 'SELECT * FROM student WHERE ' . implode(' OR ', $conditions);

Each keyword receives its own named placeholder. The wildcard characters are added to the parameter value, not injected into SQL syntax.

Exact-match search

$stmt = $dbo->prepare('SELECT * FROM student WHERE name = :name');
$stmt->execute([':name' => $searchText]);

Complete PDO example

<?php
require &#x27;config.php';

$searchText = trim($_POST[&#x27;search_text'] ?? '');
$type = $_POST[&#x27;type'] ?? 'any';
$rows = [];

if ($searchText !== &#x27;') {
    if ($type === &#x27;exact') {
        $stmt = $dbo->prepare(&#x27;SELECT * FROM student WHERE name = :name');
        $stmt->execute([&#x27;:name' => $searchText]);
    } else {
        $keywords = preg_split(&#x27;/\s+/', $searchText, -1, PREG_SPLIT_NO_EMPTY);
        $conditions = [];
        $params = [];

        foreach ($keywords as $i => $word) {
            $name = &#x27;:kw' . $i;
            $conditions[] = &#x27;name LIKE ' . $name;
            $params[$name] = &#x27;%' . $word . '%';
        }

        if ($conditions) {
            $sql = &#x27;SELECT * FROM student WHERE ' . implode(' OR ', $conditions);
            $stmt = $dbo->prepare($sql);
            $stmt->execute($params);
        }
    }

    if (isset($stmt)) {
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>

This replaces the older string-concatenation approach and avoids SQL injection while preserving the original exact-match versus match-anywhere behavior.

For larger text-search workloads, also compare FULLTEXT MATCH ... AGAINST and REGEXP.

AJAX keyword search with MySQL

Download the original keyword-search package




Subscribe to our YouTube Channel here



plus2net.com
P Biggs

13-02-2009

Thanks for your code on search-keyword.php. I've extended it to include an 'all' type for the search which is probably the most useful of the three, that returns results if all keywords are found in a record. If you want to use it or any part you're most welcome. It's on my site (see email address) in the miscellaneous section.
Ragz

10-03-2009

Thanks for the code.. it saved my academic life
A Marie

14-04-2009

Where do you put the "all" to search all tables?
A Marie

15-04-2009

When I do a search the search string also shows up.. how do I hide this without damaging the code?
smo

15-04-2009

There is a line saying echo $query; Remove this line or comment it like this //echo $query; This line is kept so before integrating the developer can know what is going to come
ramesh dudala

23-07-2009

hai this is code is easly and good so thank u
chris

02-08-2009

This is Great lesson. I was wondering also how I could add a message in case the return is false?
Hugh

21-08-2009

Where do I put the connect??
sangi

08-12-2009

hey this is really good thanks dude
Pranjal

14-01-2010

how do i display the data which is not found?
glaize

17-01-2010

tnx plus2net!i have learned a lot.
Lashan

07-02-2010

Excellent tutorial. Explained very clearly. All the best and keep it up.
Lashan Jayawardhana

13-02-2010

Excellent code plus2net. It is very useful. Fantastic work and great explanation. Keep up the good work. All the best !!!
Thajul Hussain

02-03-2010

its very usefull, working fine. thanks a lot.........
Mangal

08-04-2010

thanks for sharing this script.
sunil

11-04-2010

how to match mysql database table vlaue whose given by user in php text..
spencalot

14-04-2010

This is a great search engine. Thanks. my SQL table contains a field with key words such as: "apples fruits john doe car keys John Smith" How can I make the search engine search for "John Doe"? thanks!
smo

15-04-2010

As your query has two words John
Om Bahadur kc

14-08-2012

How to search from 2 or more table by one query without join Query,..
anil

14-09-2012

hello dude its superv query...that u used...it realy works....realy thanks
vaibhav

25-06-2016

sir, this was a great code.
I changed dbo to mysqli as :
<?php
$dbo = mysqli_connect('localhost','root','','test');
?>

now all the records are there for view only but when I search the keyword its not working.
how do I change the mail file to show search results
smo1234

02-04-2017

To use MySQLI respective functions are to be changed. By just changing connection it is not going to work.
Angie

10-10-2018

Why do I receive Data Error?? Its not working for me..
smo1234

12-02-2019

Your length of the variable $search_text is 0. You are not receiving the search text in your PHP script area.




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer