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.
This example uses PHP trim functions, string splitting, loops and PDO. For result presentation, see displaying MySQL data and pagination.
$searchText = trim($searchText);
$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.
$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.
$stmt = $dbo->prepare('SELECT * FROM student WHERE name = :name');
$stmt->execute([':name' => $searchText]);
<?php
require 'config.php';
$searchText = trim($_POST['search_text'] ?? '');
$type = $_POST['type'] ?? 'any';
$rows = [];
if ($searchText !== '') {
if ($type === 'exact') {
$stmt = $dbo->prepare('SELECT * FROM student WHERE name = :name');
$stmt->execute([':name' => $searchText]);
} else {
$keywords = preg_split('/\s+/', $searchText, -1, PREG_SPLIT_NO_EMPTY);
$conditions = [];
$params = [];
foreach ($keywords as $i => $word) {
$name = ':kw' . $i;
$conditions[] = 'name LIKE ' . $name;
$params[$name] = '%' . $word . '%';
}
if ($conditions) {
$sql = '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.
AJAX keyword search with MySQL
Download the original keyword-search package
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| 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. | |