我有这两个问题:
$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));
好的,我只想知道,我应该为每个案例写两次这些查询吗?或者我可以根据该条件创建动态查询吗?
答案 0 :(得分: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);
}