Construct MySQL WHERE with array loop
Here’s a quick way to construct the WHERE parameters when snagging data out of a MySQL database using data from an entry form. In this example, I didn’t not include the $_GET, $_POST, or $_REQUEST as I am lazy and the current code I’m working on is using some Smarty thing to get around it.
<?
$wherefields = array (search_purpose, search_type, search_price_min, search_price_max, search_bedroom,search_buildingstyle,search_city,search_state,search_zip,search_radius);
$j=0;
foreach( $wherefields as $i => $value){
if ($$wherefields[$i])
{
$sqlwhere[$j] = "$wherefields[$i] = ‘". $$wherefields[$i]."’";
$j++;
}
}
if ($sqlwhere)
{
$where = "WHERE ";
}
$where .= implode(" and ", $sqlwhere);
print_r( $sqlwhere);
echo "<br>$where";
?>