Artco News wrote:
From a form I have a list of fields, e.g:
name
address
phone
memo
I know how I do it manually for search query but how do I do it
automatically.
select * from <table_name> where
name = %$_POST['name']% and/or
address LIKE %$_POST['address']% and/or
phone LIKE %$_POST['phone']% and/or
memo LIKE %$_POST['memo']%
but my trouble if one of them is blank. Thanks
A simple way to do it :
function getPostVar($varName, $default='')
{
if (isset($_POST[$varName])) {
$var = $_POST[$varName];
}
else {
$var = $default;
}
return $var;
}
function buildWhereClause($name, $adressAndOr,
$address, $phoneAndOr,
$phone, $memoAndOr, $memo)
{
$with_name = strlen($name) > 0;
$with_address = strlen($address) > 0;
$with_phone = strlen($phone) > 0;
$with_memo = strlen($memo) > 0;
$clause = '';
if ($with_name || $with_address || $with_phone || $with_memo) {
$clause = " where ";
if ($with_name) {
$clause .= " name = '$name' ";
if ($with_address) {
$clause .= $adressAndOr;
}
}
if ($with_address) {
$clause .= " address like %'$address' ";
if ($with_phone) {
$clause .= $phoneAndOr;
}
}
/* etc ... */
}
return $clause;
}
/* possible use... */
$where = buildWhereClause(getPostVar('name'), 'and',
getPostVar('address'), 'or',
getPostVar('phone'), 'and',
getPostVar('memo'));
$query = "select * from table_name " . $where;
Note that you should add some code to the getPostVar() function to make
sure no one is trying to attack your system.
HTH
Bruno