在表单中,用户需要检查将收到简报的选项,例如:
<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" />
但我有问题如何使用选中的选项
为db创建查询到目前为止,我有这个代码,但它并不好,因为时事通讯必须一直是1,之后我有OR,因为当我把AND而不能得到我需要的结果时:
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."
";
答案 0 :(得分:1)
我想你需要这样的东西:
$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 :(得分:0)
以下是如何解决问题,使用一个变量构建where子句,在添加第一个条件时使用AND
operater,否则使用OR
$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."'";