我有一个表单中的输入,它发送一个ajax请求(带有serializeArray()
),并根据这些检查的输入,查询得到不同的数据(如过滤器)。但是我在处理这些动态条件时遇到了问题,如果它只有1(AND
)它正在工作,但由于某种原因它会超过1它会抛出一个错误(显然一切都很好):
MySQLi failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't2.type = 2
OR t2.type = 3
LIMIT ?,' at line 5<br><br />
问题必须是如何创建变量或如何在prepare()
语句中打印:
$filter_type = isset( $_POST['type'] ) ? filter_input( INPUT_POST , 'type', FILTER_SANITIZE_NUMBER_INT , FILTER_REQUIRE_ARRAY ) : NULL;
if ($filter_type != NULL) {
foreach ($filter_type as $type=>$value) {
if ($type === 0) {
$type_cond = "\nAND t2.type = " . $value; // (int) instead of filter_input()?
} else {
$type_cond .= $type_cond . "\nOR t2.type = " . $value;
}
}
}
// I manually set $table, based on post (but not directly)
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1
INNER JOIN property t2 ON t2.id = t1.id
WHERE t2.use = ?
' . $type_cond
. $filter_status
. $filter_bhk
. $filter_city
. $filter_zone . '
LIMIT ?, ?')) {
问题出在哪里?
编辑:预期的实际查询,在选中2个复选框后将是$filter_type = array(2, 3)
所以:
SELECT t1.id, t2.*
FROM for_sale t1
INNER JOIN property t2 ON t2.id = t1.id
WHERE t2.use = 1AND t2.type = 2
OR t2.type = 3
-- $filter_status = NULL; but not printing
-- $filter_bhk = NULL; but not printing
-- $filter_city = NULL; but not printing
-- $filter_zone = NULL; but not printing
LIMIT ?, ?
由@MarcB修改(在评论中)。
$filter_type = "\nAND t2.ty...";