1

I am trying to find a way to insert a value into one of two columns depending on which one is NULL.

$accept_sth = $dbh->prepare("UPDATE user_properties 
    IF(followup_offer <> NULL, fstatus=?)
    ELSE (istatus=?) 
    WHERE id=?");

$accept_sth->execute($_POST['option'], $_POST['id']);

I am doing it wrong.

8
  • 2
    Put your conditional logic in the php, not in the sql statement. Modify your SQL statement based on the condition of followup_offer in the php. Commented Sep 20, 2013 at 23:25
  • but then I would have to query the database to find out if followup_offer is NULL right. I was wanting to do it in one query. Commented Sep 20, 2013 at 23:27
  • Get followup_offer in one of your existing / previous queries. You have status and id, so get followup_offer at that same time. Commented Sep 20, 2013 at 23:30
  • well, ok I could do that. is it not possible to do the if? Commented Sep 20, 2013 at 23:33
  • 2
    It may be possible, but it will require some unnecessary brain damage to get it right, and it's going to make for a messy sql statement. Simple is better, if possible. Commented Sep 20, 2013 at 23:37

1 Answer 1

3

No ...brain damage... necessary. You can do it with a query

UPDATE user_properties 
   SET fstatus = IF(followup_offer IS NULL, fstatus, ?),
       istatus = IF(followup_offer IS NULL, ?, istatus)
 WHERE id = ?

Note: the only possible drawback for some scenarios of this type of query with conditional SET is that both columns are updated every time (one with a value and one with the old one).

Here is SQLFiddle demo

Sign up to request clarification or add additional context in comments.

2 Comments

Although I went with another solution that works (omitting the IF all together) this is the answer to the question I had. I don't see a big issue with both columns being updated. Thank you!
Brain damage, good grief. The comment suggesting splitting data-logic between PHP and MySQL is a terrible recommendation. This is an excellent answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.