2016-06-14 57 views
2

我有兩個疑問:如何根據條件將一些項目添加到數組中?

$db 
->prepare("UPDATE users 
      SET reputation = reputation + (CASE id WHEN ? THEN 2 WHEN ? THEN 15 END), 
       Money  = Money  + (CASE id WHEN ? THEN ? WHEN ? THEN ? END) 
      WHERE id IN (?, ?); ") 
->execute(array($author_ques_id, $author_ans_id, 
       $author_ques_id, $asker_amount, $author_ans_id, $responder_amount, 
       $author_ans_id, $author_ques_id)); 


$db 
->prepare("INSERT INTO events (type, score, post_id, table_code, user_id, author_id, date_time) 
         VALUES (4 , 2 , ?  , 15  , ?  , ?  , UNIX_TIMESTAMP()), 
           (4 , 15 , ?  , 15  , ?  , ?  , UNIX_TIMESTAMP()), 
           (5 , ? , ?  , 15  , ?  , ?  , UNIX_TIMESTAMP()), 
           (5 , ? , ?  , 15  , ?  , ?  , UNIX_TIMESTAMP())") 
->execute(array($answer_id, $author_ques_id, $author_ques_id, 
       $answer_id, $author_ques_id, $author_ans_id, 
       $asker_amount, $ques_id, $author_ques_id, $author_ques_id, 
       $responder_amount, $answer_id, $author_ques_id, $author_ans_id)); 

這兩個以上的查詢應該是正確的,當這個條件爲真:

if ($author_ques_id != $author_ans_id) { 
    // then queries above are fine 
} else { 
    // queries should be like below 
} 

正如我評論中的條件之上,如果這一條件是 ,那麼這兩個查詢應該是這樣的:

$db 
->prepare("UPDATE users 
      SET reputation = reputation + 2, 
       Money  = Money  + ? 
      WHERE id ?; ") 
->execute(array($asker_amount, 
       $author_ques_id)); 


$db 
->prepare("INSERT INTO events (type, score, post_id, table_code, user_id, author_id, date_time) 
         VALUES (4 , 2 , ?  , 15  , ?  , ?  , UNIX_TIMESTAMP()), 
           (5 , ? , ?  , 15  , ?  , ?  , UNIX_TIMESTAMP())") 
->execute(array($answer_id, $author_ques_id, $author_ques_id, 
       $asker_amount, $ques_id, $author_ques_id, $author_ques_id)); 

好的,我只想知道,sh我應該爲每個案例寫兩次這些查詢嗎?或者我可以根據這種情況創建一個動態查詢?

+0

這是匆忙變得凌亂。你確定沒有辦法做到這一點,而不依靠'CASE'聲明這麼重要?在一個事務內部的一系列簡單的'UPDATE'語句通常比這樣一個複雜的SQL塊更好。 – tadman

回答

0

你的查詢是完全不同的,所以讓他們分開,併爲每個案例寫下他們,至少更新聲明。

對於插入,您可以在if-else中定義值並將它們寫入數組,然後迭代數組以將一行插入另一行。像這樣

if($x ===true){ 
    $update = "...."; 
    $values = array(array(1,"b",3,4), array(5,6,7,8)); 
}else{ 
    $update = "...."; 
    $values = array(array(0,0,"c",6)); 
} 
$insert = $pdo->prepare('INTO table (col1, col2, col3, col4) VALUES (?,?,?,?)'); 
foreach($values as $row){ 
    $insert->execute($row); 
} 
相關問題