簡體   English   中英

如何根據條件將某些項目添加到數組?

[英]How can I add some items to an array based on a condition?

我有以下兩個查詢:

$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
}

正如我在上面的條件中評論的那樣,如果該條件為false ,則這兩個查詢應類似於以下內容:

$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));

好的,我想知道的是,對於每種情況,我應該兩次編寫這些查詢嗎? 還是可以基於該條件創建動態查詢?

您的查詢是完全不同的,因此請將它們分開並針對每種情況(至少是update語句)編寫它們。

對於插入,您可以在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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM