MySQL Forums
Forum List  »  PHP

Re: Searching MySQL with PHP
Posted by: Roland Bouman
Date: August 10, 2005 12:34PM

In this case, i would recommend to tackle this when you are generating your query:


$sql = "select id,description,color from tablename";

$condition = 0;

$fieldname = 'description';
if (isset($_REQUEST[$fieldname])){
$fieldvalue = $_REQUEST[$fieldname];
if ($fieldvalue!=''){
if ($condition==0){
$sql .= ' WHERE ';
} else {
$sql .= ' OR ';
}
$sql .= $fieldname.'= \''.mysql_real_escape_string($fieldvalue).'\'';
$condition++;
}
}
$fieldname = 'color';
if (isset($_REQUEST[$fieldname])){
$fieldvalue = $_REQUEST[$fieldname];
if ($fieldvalue!=''){
if ($condition==0){
$sql .= ' WHERE ';
} else {
$sql .= ' OR ';
}
$sql .= $fieldname.'= \''.mysql_real_escape_string($fieldvalue).'\'';
$condition++;
}
}

of course, we are now repeating a bit of code. It's probably wiser to put that in a function and call the function instead of repeating it all.

You could also solve it in the query, but this could well be a slower executing query:

$sql="select id, description, color from tablename where"
." description = if('".$_REQUEST["description"]."'='',description,'".$_REQUEST["description"]."') or color = if('".$_REQUEST["color"]."'='',color,'".$_REQUEST["color"]."')"
;

Options: ReplyQuote


Subject
Written By
Posted
August 10, 2005 08:53AM
Re: Searching MySQL with PHP
August 10, 2005 12:34PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.