How can I use ON DUPLICATE KEY UPDATE in PDO with mysql?

前端 未结 2 1545
野趣味
野趣味 2020-12-17 05:59

DETAILS

I am doing a single insert for the expiry of a new or renewed licence. The time period for the expiry is 2 years from the insertion date. If

相关标签:
2条回答
  • 2020-12-17 06:18

    You can use MySQL's VALUES() function:

    In an INSERT ... ON DUPLICATE KEY UPDATE statement, you can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the statement. In other words, VALUES(col_name) in the UPDATE clause refers to the value of col_name that would be inserted, had no duplicate-key conflict occurred.

    Therefore, in your case:

    ON DUPLICATE KEY UPDATE expiry = VALUES(expiry)
    

    Alternatively, you can create a fourth parameter to which you bind $expiry again:

    $sql = "INSERT INTO $table (user_id, licence, expiry)
                            VALUES (
                            :user_id,
                            :licence,
                            :expiry)
        ON DUPLICATE KEY UPDATE expiry = :another";
    
    
    try {
        $dbh = new PDO('login info here');
        $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':user_id', $userID , PDO::PARAM_INT);
        $stmt->bindParam(':licence', $licence, PDO::PARAM_STR);
        $stmt->bindParam(':expiry' , $expiry , PDO::PARAM_STR);
        $stmt->bindParam(':another', $expiry , PDO::PARAM_STR);
        $stmt->execute();
        // etc.
    
    0 讨论(0)
  • 2020-12-17 06:24

    I know you have answer below, but i had same problem and my solution looks quite different but it works for me so if you want to use different statement of using insert in mysql with explicit binding values to columns you can try this code

    $sql = "
       INSERT INTO 
          $table 
       SET
          user_id = :user_id,
          licence = :licence,
          expiry  = :expiry
       ON DUPLICATE KEY UPDATE 
          expiry = :expiry
    ";
    
    $dbh = new PDO('login info here');
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $stmt = $dbh->prepare($sql);
    $stmt->bindValue('user_id', $userID , PDO::PARAM_INT);
    $stmt->bindValue('licence', $licence, PDO::PARAM_STR);
    $stmt->bindValue('expiry' , $expiry , PDO::PARAM_STR);
    
    0 讨论(0)
提交回复
热议问题