phppostgresqlif-statementprepared-statementupsert

Problems with my attempt to implement an UPSERT


I'm having this problem when checking a condition to update a table in PostgreSQL. It has to check if the user download this once and if yes, add +1 in acessos.

<?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();
}
?>

Solution

  • You refer to $arr but it's not evident from your posted code where that is assigned. Either way, if you want to increase the current value of acessos by 1, this approach is completely unsafe in a multi-user environment.

    You are also completely open to SQL injection. Use prepared statements instead.

    Since Postgres 9.5 (!) you can do this in a single statement with the UPSERT implementation INSERT ... ON CONFLICT ... DO UPDATE. Requires a UNIQUE or PRIMARY KEY constraint on (nome, email):

    $sql = 'INSERT INTO downloads AS d (nome, email, estado, arquivo, acessos)
            VALUES ($1, $2, $3, $4, 1)
            ON     CONFLICT ON (nome, email) DO UPDATE 
            SET    acessos = excluded.acessos + 1';
    

    For repeated calls, you might use pg_prepare and pg_execute. For a single call use pg_query_params:

    pg_query_params($sql, array($_POST[nome_download]
                              , $_POST[email_download]
                              , $_POST[estado_download]
                              , $_SESSION[nome_arquivo_download]));