Forum Moderators: coopster
$sql = "SELECT idCustomer, firstname, lastname, address1_street, address2_no, county, home_phone FROM persons WHERE ";
// expand sql string conditionally if given form field is filled out
if(!empty($_POST['firstname']))
{ $sql .= " (UPPER(firstname) LIKE'". mysql_real_escape_string(trim(strtoupper($_POST['firstname'])))."' AND ";
}
if(!empty($_POST['surname']))
{ $sql .= " (UPPER(lastname) LIKE'". mysql_real_escape_string(trim(strtoupper($_POST['surname'])))."' AND ";
}
if(!empty($_POST['address']))
{ $sql .= " UPPER(address1_street) LIKE'".mysql_real_escape_string(trim(strtoupper($_POST['address'])))."' AND ";
}
if(!empty($_POST['phone']))
{
$phone = mysql_real_escape_string(trim($_POST['phone']));
$sql .= "(home_phone LIKE'".$phone."' OR work_phone LIKE'".$phone."' OR mobile_phone1 LIKE'".$phone."' OR mobile_phone2 LIKE'".$phone."') AND ";
}
$sql .= " idCustomer <> NULL"; // this is just to add something to the end of the sql string because of the ANDs
//query database
$result=mysql_query($sql);
$count=mysql_num_rows($result); //here i get an error saying mysql_num_rows() expects parameter 1 to be resource, boolean given...
// this is just to add something to the end of the sql string because of the ANDs
$where = null;
// FORM FIELDS as keys, DB FIELDS as values.
$possible_vars = Array(
'fname' => 'firstname',
'lname' => 'surname',
'addr' => 'address',
'ph' => 'phone'
);
//
foreach ($possible_vars as $key => $value) {
if (! empty($_POST[$key])) {
// Only add AND if $where has already begun
if ($where) { $where .= " and"; }
if ($key == 'ph') {
$phone = mysql_real_escape_string(trim($_POST[$key]));
$where .= " (home_phone = '".$phone."' OR work_phone = '".$phone.
"' OR mobile_phone1 = '".$phone."' OR mobile_phone2 = '".$phone."')";
}
else { $where .= " upper($value) = '" . mysql_real_escape_string(trim(strtoupper($_POST[$value]))) . "'"; }
}
}
$sql = "SELECT idCustomer, firstname, lastname, address1_street, address2_no, county, home_phone FROM persons";
if ($where) { $sql .= " where $where"; }
// echo $sql; exit; // use this to check it
$result=mysql_query($sql) or die("Cannot execute query: " . mysql_error());
$count=mysql_num_rows($result);