PDO update query with conditional?

Posted by dmontain on Stack Overflow See other posts from Stack Overflow or by dmontain
Published on 2010-04-28T03:08:11Z Indexed on 2010/04/28 4:53 UTC
Read the original article Hit count: 306

I have a PDO mysql that updates 3 fields.

$update = $mypdo->prepare("UPDATE tablename SET field1=:field1, 
                                                field2=:field2, 
                                                field3=:field3 
                                            WHERE key=:key");

But I want field3 to be updated only when $update3 = true; (meaning that the update of field3 is controlled by a conditional statement)

Is this possible to accomplish with a single query?

I could do it with 2 queries where I update field1 and field2 then check the boolean and update field3 if needed in a separate query.

//run this query to update only fields 1 and 2
$update_part1 = $mypdo->prepare("UPDATE tablename SET field1=:field1, 
                                                      field2=:field2
                                                  WHERE key=:key");

//if field3 should be update, run a separate query to update it separately
if ($update3){
  $update_part2 = $mypdo->prepare("UPDATE tablename SET field3=:field3 
                                                    WHERE key=:key");
}

But hopefully there is a way to accomplish this in 1 query?

© Stack Overflow or respective owner

Related posts about mysql

Related posts about pdo