简体   繁体   中英

How to INSERT based on a condition?

I have these INSERT query:

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

As you see, query above inserts two rows into events table. Now I need to put a condition on the way of second row. I mean if $condition is true then inserts second rows, else it shouldn't insert second row. (first row always should be inserted) .

Note: $condition always is containing a boolean value.

Well, how can I put that condition on the way of second row inserting?

You could use a insert select statement like this:

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

Since the $condition is a php variable why not do it in PHP like so:

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

Whats wrong with doing it in 2 queries?

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

You can build query string and values array before preparing and executing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM