Stack Stack - 5 months ago 29
SQL Question

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?

Answer

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