20

I'd like to switch PDO INSERT and UPDATE prepared statements to INSERT and ON DUPLICATE KEY UPDATE since I think it'll be a lot more efficient than what I'm currently doing, but I'm having trouble figuring out the correct syntax to use with named placeholders and bindParam.

I found several similar question on SO, but I'm new to PDO and couldn't successfully adapt the code for my criteria. This is what I've tried, but it doesn't work (it doesn't insert or update):

try { 
  $stmt = $conn->prepare('INSERT INTO customer_info (user_id, fname, lname) VALUES(:user_id, :fname, :lname)'          
 'ON DUPLICATE KEY UPDATE customer_info SET fname= :fname, 
                                            lname= :lname   
                                            WHERE user_id = :user_id'); 
  $stmt->bindParam(':user_id', $user_id);  
  $stmt->bindParam(':fname', $_POST['fname'], PDO::PARAM_STR);
  $stmt->bindParam(':lname', $_POST['lname'], PDO::PARAM_STR);      
  $stmt->execute();
}

This is a simplified version of my code (I have several queries, and each query has between 20 - 50 fields). I'm currently updating first and checking if the number of rows updated is greater than 0 and if not then running the Insert, and each of those queries has it's own set of bindParam statements.

9
  • Don't reuse the same placeholder in multiple places in the same query. Is your PDO connection set to throw exceptions? Unless you have a real need for bindParam, bindValue or passing parameters through execute is a better choice.
    – DCoder
    Dec 30, 2012 at 7:42
  • When you say that I shouldn't reuse the same placeholder in multiple places, do you mean that I need to have 2 sets of bindParam statements? I have it set currently with - catch(PDOException $e) {echo 'Error: ' . $e->getMessage();} - and I'm not getting any error messages for this code. Dec 30, 2012 at 7:47
  • 1
    Just putting try/catch around the query is not enough. See Error Handling and configure it to throw exceptions on errors.
    – DCoder
    Dec 30, 2012 at 7:57
  • @DCoder: Would you mind elaborating on what you mean? I thought the way I'm doing it is in line with ERRMODE_EXCEPTION in the manual, which should throw a PDOException. Dec 30, 2012 at 15:44
  • 1
    See this question for differences between bindParam and bindValue. $stmt->execute(array(':fname' => $_POST['fname'])) can also be used to pass bound variables. In my opinion, execute is the simplest option and should be preferred unless you need the specific behaviours of bindParam or bindValue. Your mileage may vary, of course.
    – DCoder
    Dec 30, 2012 at 16:37

2 Answers 2

27

IMHO below is the right answer for anyone coming across this again.
Note: this statement assumes user_id is a KEY in the table.

The STATEMENT indeed was wrong, but the accepted answer was not completely correct.

If you're inserting and updating using the same values (and not updating with different values), this is the query pseudo-code corrected:

try { 
    //optional if your DB driver supports transactions
    $conn->beginTransaction();

    $stmt = $conn->prepare('INSERT INTO customer_info (user_id, fname, lname) ' . 
                'VALUES(:user_id, :fname, :lname)' .
                'ON DUPLICATE KEY UPDATE fname=VALUES(fname), lname=VALUES(lname)');
    $stmt->bindParam(':user_id', $user_id);  
    $stmt->bindParam(':fname', $_POST['fname'], PDO::PARAM_STR);
    $stmt->bindParam(':lname', $_POST['lname'], PDO::PARAM_STR);      
    $stmt->execute();

    //again optional if on MyIASM or DB that doesn't support transactions
    $conn->commit();
} catch (PDOException $e) {
    //optional as above:
    $conn->rollback();

    //handle your exception here $e->getMessage() or something
}
3
  • 7
    +1 I agree that using VALUES() is easier when you need to use parameters. But as a side issue, fwiw you don't need to break your string in PHP like you do in Java. You can put a multi-line string into a single set of quotes. Feb 13, 2014 at 1:49
  • @BillKarwin Is correct, but we like to wrap our lines to 80 or 100 characters in our company :-)
    – akahunahi
    Feb 13, 2014 at 18:49
  • 1
    Very elegant solution using VALUES() again, instead of duplicating field names without an extra suffix. It will be deprecated soon and can be simplified by just using the field name. mysql docs. Jan 27, 2021 at 11:49
26

Your ON DUPLICATE KEY syntax is not correct.

$stmt = $conn->prepare('INSERT INTO customer_info (user_id, fname, lname) VALUES(:user_id, :fname, :lname)
    ON DUPLICATE KEY UPDATE fname= :fname2, lname= :lname2');

$stmt->bindParam(':user_id', $user_id);  
$stmt->bindParam(':fname', $_POST['fname'], PDO::PARAM_STR);
$stmt->bindParam(':lname', $_POST['lname'], PDO::PARAM_STR);      
$stmt->bindParam(':fname2', $_POST['fname'], PDO::PARAM_STR);
$stmt->bindParam(':lname2', $_POST['lname'], PDO::PARAM_STR);      

You don't need to put the table name or SET in the ON DUPLICATE KEY clause, and you don't need a WHERE clause (it always updates the record with the duplicate key).

See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html

You also had a PHP syntax error: you split the query up into two strings.

UPDATE:

To bind multiple parameters:

function bindMultiple($stmt, $params, &$variable, $type) {
  foreach ($params as $param) {
    $stmt->bindParam($param, $variable, $type);
  }
}

Then call it:

bindMultiple($stmt, array(':fname', ':fname2'), $_POST['fname'], PDO::PARAM_STR);
15
  • Thank you for explaining it so clearly :-) Is there a way around having to create two bindParam statements for each parameter? Dec 30, 2012 at 8:10
  • 1
    No, PDO requires each placeholder to be unique. You could write a function that takes an array of placeholders and a variable, and calls bindParam() in a loop to bind them all.
    – Barmar
    Dec 30, 2012 at 8:34
  • You're awesome :-D I'll try it out first thing in the morning :-) Dec 30, 2012 at 9:15
  • 2
    I just noticed an issue. bindParam requires the variable to be a reference. I just changed bindMultiple to reflect that.
    – Barmar
    Dec 30, 2012 at 17:43
  • 1
    Yes, just change it to use a normal parameter instead of reference. I don't think there are any performance issues, there's nothing special about doing it this way.
    – Barmar
    Dec 31, 2012 at 5:15

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.