我试图实施UPSERT的问题

时间:2016-01-03 18:42:11

标签: php postgresql if-statement prepared-statement upsert

我在检查条件以更新PostgreSQL中的表时遇到此问题。它必须检查用户是否下载了一次,如果是,请在acessos中添加+1。

<?php
$result2 = pg_query("SELECT * from downloads WHERE (nome = $_POST[nome_download] AND email = $_POST[email_download])");
if (pg_num_rows($result2) == 0){
$result = pg_query("INSERT INTO downloads (nome, email, estado, arquivo, acessos) VALUES ('$_POST[nome_download]','$_POST[email_download]','$_POST[estado_download]','$_SESSION[nome_arquivo_download]','1')");
}else{
$arr[acessos] = $arr[acessos] + 1;
$result = pg_query("UPDATE downloads SET acessos = $arr[acessos] WHERE (nome = $_POST[nome_download] AND email = $_POST[email_download])");
}


if (!$result){
echo "Não foi possível realizar o cadastro. Tente fazer o download mais tarde.";
}
else
{
echo "soft_bd";
pg_close();
}
?>

1 个答案:

答案 0 :(得分:0)

您引用的是$arr,但从您发布的代码中分配的内容并不明显。无论哪种方式,如果您想将acessos的当前值增加1,这种方法在多用户环境中完全不安全

您也完全接受 SQL注入。请改用预备语句。

Postgres 9.5 中,您甚至可以使用新的UPSERT implementation INSERT ... ON CONFLICT ON ... DO UPDATE 单一陈述 中执行此操作 - 假设有{ {1}}上的{1}}或UNIQUE约束:

PRIMARY KEY

对于重复通话,您可以使用pg_preparepg_execute。对于单个呼叫,请使用pg_query_params

(nome, email)