你能在MySQL中使用“On Duplicate Key Update”语句吗?

时间:2023-01-12 00:06:26

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?

我找不到任何关于用MySQL和PHP使用“ON DUPLICATE KEY UPDATE”的准备语句的引用。我是否认为这是不可能的?

-Jim

吉姆

3 个解决方案

#1


18  

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;
}

#2


2  

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.

您应该能够将每个SQL查询作为一条准备语句运行。我不知道为什么您认为重复密钥更新会有任何异常。先试一下,问我们是否有什么问题。

#3


0  

You can most certainly use ON DUPLICATE KEY UPDATE with PHP+MySQL. Have you tried it? If you have, what problem did you run into?

您可以使用PHP+MySQL进行重复密钥更新。你有试过吗?如果有,你遇到了什么问题?

#1


18  

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;
}

#2


2  

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.

您应该能够将每个SQL查询作为一条准备语句运行。我不知道为什么您认为重复密钥更新会有任何异常。先试一下,问我们是否有什么问题。

#3


0  

You can most certainly use ON DUPLICATE KEY UPDATE with PHP+MySQL. Have you tried it? If you have, what problem did you run into?

您可以使用PHP+MySQL进行重复密钥更新。你有试过吗?如果有,你遇到了什么问题?