gpt4 book ai didi

mysql - 如何在 PDO 中使用 ON DUPLICATE KEY UPDATE 和 mysql?

转载 作者:可可西里 更新时间:2023-11-01 07:49:59 27 4
gpt4 key购买 nike

详情

我正在为新的或更新的许可证的到期做一个单一的插入。到期时间为插入日期起 2 年。如果检测到重复项,条目将更新,到期时间等于剩余到期时间加上 2 年。

关于重复项,在下面的示例中,应该只有一行包含 user_id =55 和 licence=commercial。

表:licence_expiry

--------------------------------------------------------
| user_id | licence | expiry |
--------------------------------------------------------
| 55 | commercial | 2013-07-04 05:13:48 |
---------------------------------------------------------

用户 ID (int11)、许可证 (varchan50)、到期时间 (DATETIME)

我认为在 mysql 中你会这样写(请注意,我还没有检查代码是否在 mysql 中工作。)

INSERT INTO `licence_expiry`
(`user_id`, `licence`, `expiry`)
VALUES
(55, commercial, NOW()+ INTERVAL 2 YEAR)
ON DUPLICATE KEY UPDATE
`expiry` = `expiry` + INTERVAL 2 YEAR

问题:如何使用 PDO 执行此操作?我已经大致概述了我认为我将使用的内容,但我不确定要为 ON DUPLICATE KEY UPDATE 的到期值写什么。

$sql = "INSERT INTO $table (user_id, licence, expiry)
VALUES (
:user_id,
:licence,
:expiry)
ON DUPLICATE KEY UPDATE expiry = Something";


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->execute();
//$stmt->closeCursor(); //use this instead of $dbh = null if you will continue with another DB function
$dbh = null;
}

catch(PDOException $e)
{
$error=$e->getMessage();
}

非常感谢任何帮助。

最佳答案

您可以使用 MySQL 的 VALUES() 功能:

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

因此,在您的情况下:

ON DUPLICATE KEY UPDATE expiry = VALUES(expiry)

或者,您可以创建第四个参数来绑定(bind) $expiry再次:

$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.

关于mysql - 如何在 PDO 中使用 ON DUPLICATE KEY UPDATE 和 mysql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11390093/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com