I am by no means a PHP expert. I can read it somewhat but writing it is beyond me. I am trying to find the shortest most efficient way to write this if statement. It is for a filter on my site. The filter shows a business based on the selection the user makes. The issue is i dont know how to code it to where the user can select multiple filters. I am pretty sure it has to do with my && statements. Please look at my code and tell me what I am doing wrong. I have searched but I could not find anything that is unique to my situation.
if($tghtcrl!="" && $lsecrl!="" && $wavy!="" && $strt!="")
{
$vWhereClause .= " AND (specialty='".$wavy."' OR specialty='".$strt."' OR specialty='".$tghtcrl."' OR specialty='".$lsecrl."')";
}
else
{
if($tghtcrl!="")
{
$vWhereClause .= " AND specialty='".$tghtcrl."' ";
}
if($lsecrl!="")
{
$vWhereClause .= " AND specialty='".$lsecrl."' ";
}
if($wavy!="")
{
$vWhereClause .= " AND specialty='".$wavy."' ";
}
if($strt!="")
{
$vWhereClause .= " AND specialty='".$strt."' ";
}
}
Any help would be appreciated sirs. The else statement takes care of the singular selections and the beginning if statement takes care of selecting all 4. But what about selecting in between. I feel like the answer is staring me in my face. Code below is the updated code provided by @h2ooooooo.
if($tghtcrl!="" && $lsecrl!="" && $wavy!="" && $strt!="")
{
$vWhereClause .= " AND (specialty='".$wavy."' OR specialty='".$strt."' OR specialty='".$tghtcrl."' OR specialty='".$lsecrl."')";
}
else
{
$variables = array($tghtcrl, $lsecrl, $wavy, $strt);
foreach ($variables as $variable)
{
if ($variable!="")
{
$vWhereClause .= " AND specialty='".$variable."' ";
}
}
}
Apart from your obvious SQL injection (which you can read about with a simple google search), you can just use a loop to check through the values as so:
$values = array($tghtcrl, $lsecrl, $wavy, $strt);
$sqlValues = array();
foreach ($values as $value)
{
$value = trim($value);
if ($value != "")
{
$sqlValues[] = "specialty = '" . $value . "'";
}
}
if (!empty($sqlValues))
{
$vWhereClause .= " AND (" . implode(" OR ", $sqlValues) . ")";
}