2

我不知道如何在我的特定表上继续执行以下操作。

假设我有以下table param3 列tck, label, value. tck是我的主键。

数据每天来一次。我想更新现有的值tck,如果发送的数据包含一个新的tck,我想将它添加到表中......

我希望我足够清楚......谢谢你的帮助。

我正在使用的代码如下:

<?php try {
    $bdd = new PDO('mysql:host='.$_ENV['localhost'].';dbname=eip_tasks','root'); } catch(Exception $e) {
    die('Erreur : '.$e->getMessage()); }

$data = $_POST['field1'];

$phpArray = json_decode($data, true); foreach ($phpArray as $u) {  
        //$req = $bdd->prepare('INSERT INTO param (tck, label, value) VALUES(:tck, :label, :value)');
        $req = $bdd->prepare('UPDATE param SET value=:value WHERE tck=:tck');
        $req->execute(array(
            ':tck'=>$u['tck'],
            ':value'=>$u['value']
        )); } ?>

这是我现在使用的代码:

<?php
try
{
    $bdd = new PDO('mysql:host='.$_ENV['localhost'].';dbname=eip_tasks','root');
}
catch(Exception $e)
{
    die('Erreur : '.$e->getMessage());
}

$data = $_POST['field1'];
$phpArray = json_decode($data, true);

$sourceTck = array();
foreach ($phpArray as $u) {array_push($sourceTck, $u['tck']);
    $req = $bdd->prepare("INSERT INTO param (tck, label, value) VALUES (:tck, :label, :value) ON DUPLICATE KEY UPDATE value=:value");
    $req->execute(
        array(
            ':tck'=>$u['tck'],
            ':label'=>$u['label'],
            ':value'=>$u['value']
        )
    );
}

if(count($sourceTck) > 0){
    $sourceTckClause = implode("," , $sourceTck);
    $req = $bdd->prepare("DELETE FROM param WHERE tck NOT IN ($sourceTckClause)");
    $req->execute(); 
}


?>
4

2 回答 2

1

对行使用ON DUPLICATE KEY语法update而不是insert(如果tck存在):

$req = $bdd->prepare("
    INSERT INTO param (tck, label, value) 
        VALUES 
    (:tck, :label, :value)
    ON DUPLICATE KEY UPDATE value=:value
");

更新:也不要忘记绑定:label。作为您的评论,要删除表中而不是源中的数据,您应该将源tck值推送到数组,然后在NOT IN您的数组中运行删除查询:

$sourceTck = array();
foreach ($phpArray as $u) {
    array_push($sourceTck, $u['tck']);
    $req = $bdd->prepare("
        INSERT INTO param (tck, label, value)
            VALUES
        (:tck, :label, :value)
        ON DUPLICATE KEY UPDATE value=:value
    ");
    $req->execute(
        array(':tck'=>$u['tck'], ':label'=>$u['label'], ':value'=>$u['value'])
    );
}

我发现这个答案对准备和绑定tck值很有用,但是对于小型解决方案,您可以将数组值转换int为在这种情况下防止 sql 注入:

if(count($sourceTck) > 0){
    $sourceTckClause = implode("," , array_map('intval', $sourceTck));
    $bdd->query("DELETE FROM param WHERE tck NOT IN ($sourceTckClause)");
}
于 2013-09-20T13:07:40.403 回答
0

您想要做的称为 upsert 或合并。MySQL 确实支持它。

INSERT INTO param VALUES (:tck, :label, :value)
ON DUPLICATE KEY UPDATE value = :value
-- change :label as well? , label = :label
于 2013-09-20T13:07:25.927 回答