Issue
I'm attempting to UPDATE my postgres table on Heroku and have been blocked by the eccentricity of the UPDATE statement.
My initial guess was to say:
$query = pg_query($someDB, $updateQuery);
and then check if it is false, but to no avail. Here's the troublesome snippet:
$update_query = "UPDATE jellybeans SET $form[1]=$data[1], $form[2]=$data[2] WHERE $form[0]='$data[0]'";
echo 'attempting update: ' . $update_query . '<br>';
$update = pg_query($connect, $update_query);
echo "Rows updated: ", pg_affected_rows($update);
//if update failed, push to the table
How does one check on statements like INSERTS, DELETES, and the like? I'm surprised affected_rows doesn't return anything meaningful. Much appreciated.
*EDIT: * Using a SELECT query first yielded the best result:
$exists_query = "SELECT * FROM jellybeans WHERE $form[0]='$data[0]'";
$exists = pg_query($connect, $exists_query);
if($row = pg_fetch_row($exists)){
$update_query = "UPDATE jellybeans SET $form[1]=$data[1], $form[2]=$data[2] WHERE $form[0]='$data[0]' RETURNING *";
echo '<br>' . 'Attempting: ' . $update_query;
$update = pg_query($connect, $update_query);
}else{
$insert_query = "INSERT INTO jellybeans VALUES('$data[0]', $data[1], $data[2])";
echo '<br>' . 'Attempting: ' . $insert_query;
$insert = pg_query($connect, $insert_query);
pg_free_result($insert);
}
pg_free_result($exists);
pg_free_result($update);
From there a simple $row = pg_fetch_row($exists) gives a reliable existence check. In the future, it would probably be best to add an IF FOUND check into the query itself.
Solution
One way of knowing is to get the updated rows:
UPDATE ... WHERE condition RETURNING *;
This will return the set of rows updated, just count the number of results.
Answered By - greg Answer Checked By - Terry (sql.easybugfix Volunteer)
Post a Comment
Post a Comment