php 准备好的语句带有重复键更新 - 访问原始值(如果有的话)进行条件测试?

问题描述 投票:0回答:1

我遇到了一个独特的情况,我不确定这是否可能。 我需要访问

update
的原始值(如果有的话)并将其传递给函数来确定是否保留原始值(如果有的话)、更改它,或者在以下情况下插入默认值:条目从未存在过?

我唯一的选择是运行另一个查询来检索该值(如果存在),还是有办法访问我的绑定中的值(如果存在)以在函数中使用以确定插入/更新的值?

$stmt = $db->prepare("
    INSERT INTO accounts (
            account_id,
            version,
            update
        )
        VALUES (
            :account_id,
            :version,
            :update
       )
    ON DUPLICATE KEY UPDATE
        version = VALUE(version),
        update = VALUE(update)
");

//bindings
$binding = array(
    'account_id' => 'some id',
    'version' => 'some version',
    'update' => ### is there a way to access the original value (if there was one)?  I'd like to pass this to a function to determine what value I insert/update into the db
);

$stmt->execute($binding);
php pdo mariadb prepared-statement
1个回答
0
投票

我使用存储过程来实现这个想法。我这里的示例是 MariaDb 或可能是 MySQL。同样的事情在 MSSQL 中也同样有效。

PHP:

$stmt = $db->prepare("CALL sp_name(?,?,?);");

//bindings
$binding = array(
    'account_id' => 'some id',
    'version' => 'some version',
    'update' => ###
);

$success = $stmt->execute($binding);

SQL:

DELIMITER $$
CREATE DEFINER=user PROCEDURE `sp_name`(
    IN `_account_id` datatypeflags,
    IN `_version` datatypeflags,
    IN `_update` datatypeflags)
BEGIN

    IF EXISTS (SELECT * FROM accounts 
            WHERE version = _version,
                   update = _update )
    THEN
        //DUPLICATE KEY
        // Do the update you're looking to do or not do.
        // Yes, you have to find it again using the same condition as the EXISTS SELECT above like this.
        // Which makes no sense to do this one. So, just skip it.
        UPDATE accounts 
        SET version = _version,
               update = _update
        WHERE version = _version,
               update = _update;
    ELSE
        INSERT INTO accounts (
            account_id,
            version,
            update
        )
        VALUES (
            :_account_id,
            :_version,
            :_update
        );

    END IF;
END$$
DELIMITER ;
© www.soinside.com 2019 - 2024. All rights reserved.