所以我需要在 MySQL 中更新和设置两个数组。 item_id [1,2,3] 和 item_order[2,1,3]
这是数组插入之前的项目表:
item_id item_order
1 1 //should become 2
2 2 // should become 1
3 3 // should become 3
数组应成对插入,1-2、2-1、3-3。 如何使用准备好的语句有效地执行此操作以及如何测试数组项是否确实是数字?
最佳答案
假设您有这样的输入:
$item_id = array(1, 2, 3);
$item_order = array(2, 1, 3);
// and a PDO connection named $pdo
你可以尝试这样的事情。 (我还假设您已将 PDO 配置为 throw exceptions when problems arise )。
function all_numbers($input) {
foreach($input as $o) {
if(!is_numeric($o)) {
return false;
}
}
return true;
}
if(count($item_id) != count($item_order)) {
throw new Exception("Input size mismatch!");
}
if(!all_numbers($item_id) || !all_numbers($item_order)) {
throw new Exception("Invalid input format!");
}
$pairs = array_combine($item_id, $item_order);
// now $pairs will be an array(1 => 2, 2 => 1, 3 => 3);
if($pdo->beginTransaction()) {
try {
$stmt = $pdo->prepare('UPDATE `items` SET `item_order` = :order WHERE `item_id` = :id');
foreach($pairs as $id => $order) {
$stmt->execute(array(
':id' => $id,
':order' => $order,
));
}
$pdo->commit();
} catch (Exception $E) {
$tx->rollback();
throw $E;
}
} else {
throw new Exception("PDO transaction failed: " . print_r($pdo->errorInfo(), true));
}
但最好重新设计您的输入 - 仅按所需顺序传递 item_ids
并自动计算其 item_order
值。
关于mysql - PDO - 更新和设置查询(2 个数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10855496/