我在 PHP 中有函数,它应该在 MySQL IN 语句中绑定这么多变量,即在数组中。我的问题是变量和键正在改变,但函数只绑定最后一个值 n 次。
我不知道问题出在哪里...
这是我的课堂方法:
public function getOtListByOtNumbers($conditions){
$data_array = $conditions[SEARCH_OT];
# To find last key (remove coma)
$quantity = count($data_array);
$marks = '';
# Bind name string && rewriting value as integer
foreach ($data_array as $key => $value){
$i = $key+1;
if ($i == $quantity){
$marks .= ':key'.$i;
}
else {
$marks .= ':key'.$i.', ';
}
}
# Query
$sql="
SELECT
c_int_id,
c_ot,
c_tickets_amount,
c_basket_value,
c_person,
c_company,
c_city,
c_package_number,
c_delivery_method,
c_ot_date,
c_email,
c_phone,
c_comment,
c_send
FROM ws_orders
WHERE c_ot IN (".$marks.")
ORDER BY c_int_id DESC
LIMIT :first, :last ";
$stmt = $this->PDO->prepare($sql);
# Bind n values
// Here is a problem
var_dump($data_array); // var dump 1
foreach ($data_array as $key => $param){
$key_number = $key +1;
$key_name = 'key'.$key_number;
$stmt->bindParam($key_name, $param, PDO::PARAM_INT);
var_dump($key_name); // var dump 2
var_dump($param); // var dump 3
}
# Bind limit values
$stmt->bindParam('first', $conditions[OT_SEARCH_FIRST_ROW], PDO::PARAM_INT);
$stmt->bindParam('last', $conditions[OT_SEARCH_ROW_LIMIT], PDO::PARAM_INT);
# If executed return result
if ($stmt->execute() != FALSE) {
$stmt_result = $stmt->fetchAll();
$stmt->closeCursor();
var_dump($stmt_result); // var dump 4
# If not executed print debug and return FALSE
} else {
var_dump($stmt->errorInfo());
$this->debugQuery($stmt);
$stmt_result = FALSE;
}
return $stmt_result;
}
这里是 var dupms:
变量转储 1
array (size=2)
0 => string '2761531'
1 => string '2760650'
变量转储 2 & 3
string 'key1' (length=4)
string '2761531'
string 'key2' (length=4)
string '2760650'
来自此执行的 SQL 查询
SELECT
c_int_id,
c_ot,
c_tickets_amount,
c_basket_value,
c_person,
c_company,
c_city,
c_package_number,
c_delivery_method,
c_ot_date,
c_email,
c_phone,
c_comment,
c_send
FROM ws_orders
WHERE c_ot IN ('2760650', '2760650')
ORDER BY c_int_id DESC
LIMIT 0, 30
那么我做错了什么?
编辑
所以我做到了;)问题出在foreach上
代替:
foreach ($data_array as $key => $param){
$key_number = $key +1;
$key_name = 'key'.$key_number;
$stmt->bindParam($key_name, $param, PDO::PARAM_INT);
var_dump($key_name); // var dump 2
var_dump($param); // var dump 3
}
我给:
for ($key_number = 0; $key_number < $quantity + 1; $key_number++) {
$key_name = 'key'.$key_number;
$stmt->bindParam($key_name, $data_array[$key_number], PDO::PARAM_INT);
}
它有效,但我仍然不知道早期 foreach 的问题是什么......