Dynamic Database Search with Optional Filters

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.

Never concatenate raw form values into SQL. Prepared statements handle values; column names, operators and sort directions must come from your own allow-list.

Build conditions instead of trimming AND/OR text

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);
?>

Multiple words in a name search

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




Subscribe to our YouTube Channel here



plus2net.com
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.




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