2012-06-01 20 views
0

所以我有兩個數組,我需要在MySQL中更新和設置。 ITEM_ID [1,2,3]和item_order [2,1,3]PDO - 更新和設置查詢(2個數組)

這裏是數組插入之前的項目表:

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。 我怎樣纔能有效地準備好聲明,如何測試數組項是否確實是數字?

回答

1

假設你有輸入這樣的:

$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值。

+0

感謝DCoder,請試試看。但是,您準確地重新確定輸入的含義是什麼?你能給我舉個例子嗎? – Wonka

+0

@Wonka:我的意思是,您應該按照正確的順序傳遞id,並讓插入循環生成實際的$ order值。看看[jQuery Sortable的'toArray'](http://jqueryui.com/demos/sortable/#method-toArray)方法。 – DCoder

+0

作品像一個魅力,謝謝你的幫助! – Wonka

1

下面是一個例子:

UPDATE MYTABLE SET MyField的= CASE other_field WHEN 1 THEN '值' WHEN 2 THEN '值' WHEN 3 THEN '值' END WHERE ID IN(1 ,2,3)

+0

這是很多情況下:)仍然在尋找更多的答案:) – Wonka

+1

你是否有任何服務器端腳本,例如PHP或只是MySQL? – codingbiz

+0

@tunmisefasipe php和mysql :) – Wonka