我的 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;