如何在WHERE子句中使用变量来进行SQL SELECT查询

时间:2013-06-10 01:18:40

标签: php mysql forms where-clause

我的SQL SELECT查询有3个由HTML表单设置的变量,但这些变量可以为null:

   $suburb = (isset($_POST['suburb'])) ? $_POST['suburb'] : '';
   $postcode = (isset($_POST['postcode'])) ? $_POST['postcode'] : '';
   $state = (isset($_POST['state'])) ? $_POST['state'] : '';

当在表单中输入所有3个变量时,SELECT查询处理正常(由于WHERE子句中的AND')。但是当一个或多个变量为空时,SELECT查询会在数据库中查找NULL值时出错。

我想要它做的是当变量为null时,我不想要一个where子句

查询:

$sql = <<<SQL
SELECT 
    cs.customerRefId,
    cc.firstName,
    cc.lastName,
    cc.email,
    cc.phone,
    cc.mobile,
    cs.seekingAddressSuburb, 
    cs.seekingAddressPostcode, 
    cs.seekingAddressState
FROM 
    customer_seeking cs
LEFT JOIN
    customer_contact cc ON cc.customerRefId = cs.customerRefId
WHERE
cs.seekingAddressSuburb = '$suburb' AND
cs.seekingAddressPostcode = '$postcode' AND
cs.seekingAddressState = '$state'
SQL;  


if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

例如,如果只定义了状态变量(cs.seekingAddressSuburb =&#39; $ suburb&#39; AND cs.seekingAddressPostcode =&#39; $ postcode&#39; AND将从WHERE子句中删除:

$sql = <<<SQL
SELECT 
    cs.customerRefId,
    cc.firstName,
    cc.lastName,
    cc.email,
    cc.phone,
    cc.mobile,
    cs.seekingAddressSuburb, 
    cs.seekingAddressPostcode, 
    cs.seekingAddressState
FROM 
    customer_seeking cs
LEFT JOIN
    customer_contact cc ON cc.customerRefId = cs.customerRefId
WHERE
cs.seekingAddressState = '$state'
SQL;  

2 个答案:

答案 0 :(得分:0)

在String中构造查询,然后如果每个字段都有值,则逐个添加。例如:

$query = "select * from table1 where 1=1";
if(!empty($suburb)) $query.=" and cs.seekingAddressSuburb = '$suburb'";
if(!empty($postcode)) $query.=" and cs.seekingAddressPostcode = '$postcode'";
if(!empty($state)) $query.=" and cs.seekingAddressState = '$state'";
//run your query then

答案 1 :(得分:0)

我不确定这是否是您想要做的,但您在 PHP FIDDLE

中尝试此代码
$a = 'a';
$b = 'b';
$c;

$SQL = "SELECT * FROM TABLE WHERE A = $a". (!empty($b) ? ' AND b ='. $b: '')  ." ". (!empty($c) ? 'AND C ='. $c: '');

echo $SQL;

关联您的代码

$suburb = if(isset($_POST['suburb']));
$postcode = if(isset($_POST['postcode']));
$state = if(isset($_POST['state']));

$SQL = "SELECT cs.customerRefId,
cc.firstName,
cc.lastName,
cc.email,
cc.phone,
cc.mobile,
cs.seekingAddressSuburb, 
cs.seekingAddressPostcode, 
cs.seekingAddressState
FROM 
    customer_seeking cs
LEFT JOIN
    customer_contact cc ON cc.customerRefId = cs.customerRefId WHERE cs.seekingAddressSuburb = $suburb". (!empty($postcode) ? ' AND cs.seekingAddressPostcode ='. $postcode: '')  ." ". (!empty($state) ? 'AND cs.seekingAddressState ='. $state: '');

echo $SQL;