我正在创建一个高级搜索,并希望通过将它们添加到数组中来循环查询:
private $searchFields = [
'as_first_name' => 'users.first_name like "%VALUE%"',
'as_last_name' => 'users.last_name like "%VALUE%"',
'as_payment_history_invoice_num' => 'users.user_id = (SELECT user_id from payment_history where payment_history.invoice_number = "VALUE" LIMIT 1)',
'as_building_num' => 'property_units.building_number like "%VALUE%"',
'as_residents_email' => 'users.email like "%VALUE%"',
'as_property_name' => 'property.name like "%VALUE%"',
'as_phone_num' => 'REPLACE(REPLACE(REPLACE(REPLACE(users.phone, " ", ""), "(", ""), ")", ""), "-", "") = "VALUE"',
'as_unit_num' => 'property_units.unit_number = "VALUE"',
'as_account_status' => 'user_status.status_name = "VALUE"'
];
所以在搜索中我做了类似的事情。
if (array_key_exists($key, $this->searchFields)) {
$form->get($key)->setValue($val);
$where->NEST->literal(str_replace('VALUE', urldecode($val), $this->searchFields[$key]))->UNNEST;
}
但问题是我没有逃避任何事情。不好。我如何使用相同的结构,但也可以逃避。
答案 0 :(得分:6)
Literal
谓词适用于没有占位符的情况。
您应该使用Expression
谓词。
private $searchFields = [
'as_first_name' => 'users.first_name like "?"',
'as_last_name' => 'users.last_name like "?"',
'as_payment_history_invoice_num' => 'users.user_id = (SELECT user_id from payment_history where payment_history.invoice_number = "?" LIMIT 1)',
'as_building_num' => 'property_units.building_number like "?"',
'as_residents_email' => 'users.email like "?"',
'as_property_name' => 'property.name like "?"',
'as_phone_num' => 'REPLACE(REPLACE(REPLACE(REPLACE(users.phone, " ", ""), "(", ""), ")", ""), "-", "") = "?"',
'as_unit_num' => 'property_units.unit_number = "?"',
'as_account_status' => 'user_status.status_name = "?"'
];
zend-form值应该已经被解码,因此不需要urldecode
if (array_key_exists($key, $this->searchFields)) {
$form->get($key)->setValue($val);
$where->NEST->expression($this->searchFields[$key], $val)->UNNEST;
}
我很长一段时间没有使用zend-db,请确保检查此代码是否实际产生了您需要的查询。
答案 1 :(得分:0)
您不应该使用urldecode
;它应该在你到达之前解码。听起来NEST
对于这种情况可能过于花哨。
foreach (...)
{
$val = ...; // Get the raw value from the form field ($_POST[...] or whatever)
$mval = addslashes($val);
$sf = $this->searchFields[...];
$msf = str_replace('VALUE', $mval, $sf);
... $msf ...
}
mysqli_real_escape_str
会比addslashes
好,但你需要拥有mysql连接对象;你有吗?