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

前端 未结 2 1547
野趣味
野趣味 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.
    

提交回复
热议问题