简体   繁体   中英

PHP cannot increase value in Postgres database

I could use some help understanding an odd situation. I have a postgres database 'servers' with ip (inet) and load (integer) columns. I can manually update a load value via psql as follows:

UPDATE servers 
    SET load = load + 100 
WHERE ip = '10.10.10.10';

I have written a php script to automate load updates. However, the 'value = value + x' syntax is not working for me now.

THIS WORKS:

pg_query($conn, "UPDATE servers SET load = 100 WHERE ip = '10.10.10.10'");

THIS DOESN'T:

pg_query($conn, "UPDATE servers SET load = load + 100 WHERE ip = '10.10.10.10'");

When using the latter, the script hangs indefinitely without giving a response. I have tried variations such as adding an or die(pg_last_error()) clause at the end. I have also tried using a pg_prepare and pg_execute statement. Still no output, and no change to the database.

Am I missing something? Is there an easy way to get around this (I'd rather not use a separate query to get load just so that I can add it back in).

I have solved this issue. I am not certain why this was a problem, but it turns out that best practices helped solve it in the end anyway.

Instead of running a single pg_query, I set up appropriate variables and used pg_query_params. This is probably a good idea regardless of issues.

$myQuery = "UPDATE servers SET load = load + $1 WHERE ip = '$2'";
$serverIP = '10.10.10.10';
$loadAdded = '1234';
$result = pg_query_params($conn, $myQuery, array($loadAdded, $serverIP));

Again, I don't know why this solved the issue for me, but it did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM