我有一个包含大量数据的表格。在此表中,我想添加新值并更新旧值。因此,我发现了以下方法
在根据响应调整查询后,我仍然遇到错误。
Fatal error: Uncaught PDOException: SQLSTATE[42702]: Ambiguous column: 7
ERROR: column reference "id" is ambiguous LINE 3: ...richia coli',full_name =
'Escherichia coli' WHERE id = '0' ^ in /var/www/html/Insert.php:127 Stack
trace: #0 /var/www/html/Insert.php(127): PDO->query('INSERT INTO spe...') #1
{main} thrown in /var/www/html/Insert.php on line 127
改编的查询是:
$sql = "INSERT INTO species (id,match,full_name)
VALUES ('".$var_id."','".$var_match ."','".$var_full_name."')".
"ON CONFLICT (id) DO UPDATE
SET match = '".$var_match."',full_name = '".$var_full_name."' ".
" WHERE id = '".$var_id."' ";
出于某种原因,它似乎仍然无法识别ON CONFLICT(id)DO UPDATE SET。见图 有人能告诉我,我弄错了吗?提前致谢。
答案 0 :(得分:1)
EXCLUDED.'".$var_match."'
会变成EXCLUDED.'Escherichia coli'
,而'Escherichia coli'
肯定不是一列。
使用
$sql = "INSERT INTO species (id,match,full_name)
VALUES ('".$var_id."','".$var_match ."','".$var_full_name."')".
"ON CONFLICT (id) DO UPDATE
SET match = '".$var_match."',full_name = '".$var_full_name."' ";
或
$sql = "INSERT INTO species (id,match,full_name)
VALUES ('".$var_id."','".$var_match ."','".$var_full_name."')".
"ON CONFLICT (id) DO UPDATE
SET match = EXCLUDED.match,full_name = EXCLUDED.full_name ";
您可能还错过WHERE id = '".$var_id."'
的{{1}}或WHERE id = EXCLUDED.id
。
答案 1 :(得分:0)
这是我找到的解决方案。我把查询拆分成了因为ON CONFLICT对我不起作用。首先,我使用select通过检查id是否存在来确定行是否已存在。如果存在id,则更新数据。如果该想法不存在,则添加新行。
function execute_query($query,$dbh){
if ($dbh->query($query)) {
return "New Record Inserted Successfully!<br \>\n";
}else{
return "Data not successfully Inserted.<br \>\n";
}
}
$query = 'SELECT * FROM species '. 'WHERE id = '. "'".$var_id."'";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$out = $stmt->fetch();
print_r($out) ;
if ($out !== false){
$sql = "UPDATE species SET id = '".$var_id."', match ='".$var_match."',full_name = '".$var_full_name."'
WHERE id = '".$var_id."' ";
echo $sql ."<br \>\n";;
execute_query($sql,$dbh); # function
echo "Value is updated";
}else{ ### If no result => insert new values
$sql = "INSERT INTO species (id,match,full_name)VALUES
('".$var_id."','".$var_match ."','".$var_full_name."')";
execute_query($sql,$dbh);
echo "New value is inserted";