因此,我在MySQL中有两个需要更新和设置的数组。item_id 1,2,3和item_order2,1,3
以下是数组插入之前的items表:
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。如何使用准备好的语句有效地执行此操作,以及如何测试数组项是否真的是数字?
发布于 2012-06-02 14:06:43
假设您有如下输入:
$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值。
发布于 2012-06-02 02:31:11
下面是一个示例:
更新mytable SET myfield = CASE other_field WHEN 1 THEN 'value‘WHEN 2 THEN 'value’WHEN 3 THEN 'value‘END WHERE id IN (1,2,3)
https://stackoverflow.com/questions/10855496
复制相似问题