我不知道如何在我的特定桌子上继续做以下事情。
假设我有以下table param
,其中包含3列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();
}
?>
答案 0 :(得分: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'])
);
}
我发现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)");
}
答案 1 :(得分:0)
您要做的事情称为upsert或merge。 MySQL确实支持它。
INSERT INTO param VALUES (:tck, :label, :value)
ON DUPLICATE KEY UPDATE value = :value
-- change :label as well? , label = :label