Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use a prepared statement in MySQL with "On Duplicate Key Update"?

I can't find any reference to using prepared statements with "ON DUPLICATE KEY UPDATE" with MySQL and PHP. Am I correct in thinking that this is not possible?

-Jim

like image 961
Jim H. Avatar asked May 12 '10 11:05

Jim H.


2 Answers

Here is a generalized example of this usage:

$db->prepare('
INSERT INTO tableName (id, col1, col2, col3...)
VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE  col1 = VALUES(col1),
        col2 = VALUES(col2),
        col3 = VALUES(col3)
');

$stmt->bind_param('isss',
                  $id,
                  $col1,
                  $col2,
                  $col3
                 );
$db->execute($stmt);

if ($id == null) { //If you need the auto increment from the insert.
  $newId = $stmt->insert_id;
}
like image 134
Patrick James McDougle Avatar answered Sep 20 '22 12:09

Patrick James McDougle


You should be able to run every SQL query as a prepared statement. I don't know why you think there would be any exception for ON DUPLICATE KEY UPDATE. Try it first and ask us if there are any problems.

like image 29
Emil Vikström Avatar answered Sep 22 '22 12:09

Emil Vikström