1

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

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

当在表单中输入所有 3 个变量时,SELECT 查询处理正常(由于 WHERE 子句中的 AND)。但是当一个或多个变量为空时,SELECT 查询会出错,因为它正在数据库中查找 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 = '$suburb' AND cs.seekingAddressPostcode = '$postcode' 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;  
4

2 回答 2

0

在字符串中构造您的查询,然后如果每个字段都有值,则一一添加。例子 :

$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
于 2013-06-10T01:36:03.437 回答
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;
于 2013-06-10T01:39:35.657 回答