我的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查询错误,因为它是寻找在DATABSE 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 =“$郊区” AND cs.seekingAddressPostcode =“$邮编” 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;