Dynamic search means adding only the filters a visitor actually supplies. The safe pattern is to build a list of approved SQL conditions while keeping every visitor value in a prepared-statement parameter.
The older version built one long SQL string and then removed trailing AND/OR text. An array of conditions is easier to validate and avoids broken SQL when no filter is selected.
<?php
$conditions = [];
$params = [];
if ($class !== '') {
$conditions[] = 'class = :class';
$params[':class'] = $class;
}
if ($greater !== '' && is_numeric($greater)) {
$conditions[] = 'mark > :greater';
$params[':greater'] = (float)$greater;
}
$sql = 'SELECT id, name, class, mark, sex FROM student';
if ($conditions) {
$sql .= ' WHERE ' . implode(' AND ', $conditions);
}
$sql .= ' ORDER BY id';
$stmt = $dbo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
For an “any word” search, create one placeholder per word and group the LIKE expressions with parentheses.
SELECT id, name, class, mark, sex
FROM student
WHERE class = :class
AND (name LIKE :name_0 OR name LIKE :name_1)
ORDER BY id;
For a larger free-text search requirement, see MATCH() ... AGAINST(). For a simpler name-only search, see keyword search.
Download the original database-search package Student table SQL dump
WHERE · LIKE · AND/OR · PDO · Database autocomplete
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.
| swapnil` | 19-09-2014 |
| Good example provide from you this tutorial realy help for me thanks........ | |
| skechav | 12-09-2015 |
| Thank you for this!!!It helped me a lot using it as a base to develop a more complicated search form in combination with other useful tutorials I 've studied in your site..Though It happened 2 years ago, I ended up posting this comment now..with a...."small" delay ;-) p.s : Your content rocks by the way !!! | |
| Jonathan | 01-12-2015 |
| How do I display records before running the query:? | |
| smo1234 | 03-12-2015 |
| You can't display records before. However if you want to display all the records first and then ask the user to filter it then you can simply try select query to display records. | |