如何根据条件INSERT?

时间:2016-06-15 22:18:29

标签: php mysql sql pdo

我有这些INSERT查询:

$db->prepare("INSERT INTO
              events (post_id, table_code, other_id, user_id, author_id, date_time )
              VALUES (?      , 15        , ?       , ?      , ?        , UNIX_TIMESTAMP()),
                     (?      , 15        , ?       , ?      , ?        , UNIX_TIMESTAMP())
")->execute(array($answer_id, $answer_id, $author_ques_id, $author_ques_id,
                  $answer_id, $answer_id, $author_ques_id, $author_ans_id));

如您所见,上面的查询将两行插入events表。现在我需要在第二排的路上放一个条件。我的意思是如果$condition true 然后插入第二行,否则它不应该插入第二行。 (应始终插入第一行)

注意: $condition始终包含布尔值。

那么,我怎样才能把这个条件放在第二行插入的路上?

4 个答案:

答案 0 :(得分:1)

你可以使用这样的insert select语句:

$db
->prepare("INSERT INTO
             events (post_id, table_code, other_id, user_id, author_id, date_time )
             select ?, 15, ?, ?, ?, UNIX_TIMESTAMP()
              UNION ALL
             select ?, 15, ?, ?, ?, UNIX_TIMESTAMP()
               from (select 1) as a
              where 1=?
")->execute(array($answer_id, $answer_id, $author_ques_id, $author_ques_id,
                  $answer_id, $answer_id, $author_ques_id, $author_ans_id,
                  ($yourCondition?1:0) ));

答案 1 :(得分:1)

由于$ condition是一个php变量,为什么不在PHP中这样做:

if ($condition === true) {
    $db->prepare($first_and_seccond_row);
} else {
    $db->prepare($first_row);
}

答案 2 :(得分:1)

在2次查询中做错了什么?

$query = $db->prepare("INSERT INTO
              events (post_id, table_code, other_id, user_id, author_id, date_time)
              VALUES (?, 15, ?, ?, ?, UNIX_TIMESTAMP())");

$query->execute(array($answer_id1, $answer_id1, $author_ques_id1, $author_ans_id1));

if ($condition)
    $query->execute(array($answer_id2, $answer_id2, $author_ques_id2, $author_ans_id2));

答案 3 :(得分:1)

您可以在准备和执行之前构建查询字符串和值数组。

$query = "INSERT INTO
          events (post_id, table_code, other_id, user_id, author_id, date_time )
          VALUES (?, 15, ?, ?, ?, UNIX_TIMESTAMP())";
$values = array($answer_id, $answer_id, $author_ques_id, $author_ques_id);
if ($condition) {
    $query .= ",(?, 15, ?, ?, ?, UNIX_TIMESTAMP())";
    $values = array_merge($values, array($answer_id, $answer_id, $author_ques_id, $author_ans_id);
}
$db->prepare($query)->execute($values);