Select with multiple conditions
In the form, the user needs to check the parameters that will receive the newsletter, for example:
<input type="checkbox" name="male" value="1" />
<input type="checkbox" name="female" value="1" />
<input type="checkbox" name="person" value="1" />
<input type="checkbox" name="company" value="1" />
But I have a problem creating a query for the db with the options checked
I have this code so far, but it's not good because the newsletter has to be 1 all the time, and after that I have OR, because when I put AND I don't get the results I want:
if($options['male']) {
$sqlAddMale = " OR gender = 2 ";
}
if($options['female']) {
$sqlAddFemale = " OR gender = 1 ";
}
if($options['person']) {
$sqlAddPerson = " OR VAT = '' ";
}
if($options['company']) {
$sqlAddCompany = " OR VAT <> '' ";
}
$query = "
SELECT email FROM users WHERE newsletter=1
".$sqlAddMale."
".$sqlAddFemale."
".$sqlAddPerson."
".$sqlAddCompany."
";
+3
source to share
2 answers
I think you want something like this:
$placeOr = false;
if($options['male']) {
$placeOr = true;
$sqlAddMale = " (newsletter=1 AND gender = 2) ";
}
if($options['female']) {
$sqlAddFemale = (($placeOr)?" Or ":"");
$sqlAddFemale .= " (newsletter=1 AND gender = 1) ";
$placeOr = true;
}
if($options['person']) {
$sqlAddPerson = (($placeOr)?" Or ":"");
$sqlAddPerson .= " (newsletter=1 AND VAT = '') ";
$placeOr = true;
}
if($options['company']) {
$sqlAddCompany = (($placeOr)?" Or ":"");
$sqlAddCompany .= " (newsletter=1 AND VAT <> '') ";
$placeOr = true;
}
$query = "
SELECT email FROM users WHERE
".$sqlAddMale."
".$sqlAddFemale."
".$sqlAddPerson."
".$sqlAddCompany."
";
+1
source to share
This is how you can solve your problem, use one variable to create the where clause, use AND
operater when adding the first condition, otherwise useOR
$sqlString = '';
if($options['male']) {
$sqlString = " AND gender = 2 ";
}
if($options['female']) {
if(!$sqlString) $sqlString = " AND gender = 1 ";
else
$sqlString .= " OR gender = 1 ";
}
if($options['person']) {
if(!$sqlString) $sqlString = " AND VAT = '' ";
else
$sqlString .= " OR VAT = '' ";
}
if($options['company']) {
if(!$sqlString) $sqlString = " AND VAT <> '' ";
else
$sqlString .= " OR VAT <> '' ";
}
$query = "SELECT email FROM users WHERE newsletter=1'".$sqlString."'";
0
source to share