フォームフィールドを整理している場合は、次のようにすることができます。
<?php
$fields = array(
// Form // SQL
'brand' => 'brand',
'type' => 'type',
'price' => 'price',
);
$sql = 'SELECT * FROM `database`';
$comb = ' WHERE ';
foreach($fields as $form => $sqlfield)
{
if (!isset($_POST[$form]))
continue;
if (empty($_POST[$form]))
continue;
// You can complicate your $fields structure and e.g. use an array
// with both sql field name and "acceptable regexp" to check input
// ...
// This uses the obsolete form for mysql_*
$sql .= $comb . $sqlfield . ' LIKE "%'
. mysql_real_escape_string($_POST[$form])
. '"';
/* To use PDO, you would do something like
$sql .= $comb . $sqlfield . 'LIKE ?';
$par[] = $_POST[$form];
*/
$comb = ' AND ';
}
// Other SQL to go here
$sql .= " ORDER BY brand;";
/* In PDO, after preparing query, you would bind parameters
- $par[0] is value for parameter 1 and so on.
foreach($par as $n => $value)
bindParam($n+1, '%'.$value.'%');
*/