我不知道如何在我的特定表上继续做下面的事情。
假设我有下面的table param,有3列tcklabelvaluetck是我的主键。
数据每天都有一次。我想更新现有的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();
}


?>

最佳答案

使用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。作为注释,要删除表中而非源中的数据,应将sourcetck值推送到数组中,然后运行delete查询,其中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'])
    );
}

我发现this answer对于准备和绑定tck值很有用,但是对于小的解决方案,可以将数组值转换为int以防止在这种情况下进行sql注入:
if(count($sourceTck) > 0){
    $sourceTckClause = implode("," , array_map('intval', $sourceTck));
    $bdd->query("DELETE FROM param WHERE tck NOT IN ($sourceTckClause)");
}

关于mysql - 添加或更新MySQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18917419/

10-11 01:47