PHP cannot increase value in Postgres database - php

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.

Related

PHP DB caching, without including files

I've been searching for a suitable PHP caching method for MSSQL results.
Most of the examples I can find suggest storing the results in an array, which would then get included to page. This seems great unless a request for the content was made at the same time as it being updated/rebuilt.
I was hoping to find something similar to ASP's application level variables, but far as I'm aware, PHP doesn't offer this functionality?
The problem I'm facing is I need to perform 6 queries on page to populate dropdown boxes. This happens on the vast majority of pages. It's also not an option to combine the queries. The cached data will also need to be rebuilt sporadically, when the system changes. This could be once a day, once a week or a month. Any advice will be greatly received, thanks!
You can use Redis server and phpredis PHP extension to cache results fetched from database:
$redis = new Redis();
$redis->connect('/tmp/redis.sock');
$sql = "SELECT something FROM sometable WHERE condition";
$sql_hash = md5($sql);
$redis_key = "dbcache:${sql_hash}";
$ttl = 3600; // values expire in 1 hour
if ($result = $redis->get($redis_key)) {
$result = json_decode($result, true);
} else {
$result = Db::fetchArray($sql);
$redis->setex($redis_key, $ttl, json_encode($result));
}
(Error checks skipped for clarity)

php GET requests and their subsequent use as a variable (in an SQL confdition)

I have successfully extracted the correct data from my database during testing (its just a prototype - so yes I know its not secure SQL). The test SQL is
$sql=
SELECT *
FROM jobcards
WHERE jobnumber='$jobnumber'
";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{loop}
The issue is the source of the data to which $jobnumber is set.
If during testing I set $jobnumber to the string Agen912-491 (implicitly) I get out of the database exactly what I should get out. However here is the problem.
I am clicking from a link on another page. The link creates the URL:-
domain.php/jobcard.php?jobnumber=%20Agen912-491
which take me to the page on which the SQL query (and the output) resides. So on the page I set
$jobnumber = $_GET["jobnumber"];
echo $jobnumber;//testing
to request (and test) the jobnumber (passed from the link) that I need to insert into the WHERE condition. As expected the echo correctly returns Agen912-491. So exactly the same string (it seems) as the implicit value used succesfully in testing. All good so far.
However when I then set $jobnumber= $_GET["jobnumber"]; the database query fails to find any records. [In desperation I fudged the process so that the variable $jobnumber = $_SESSION ["jobnumber"]; (and ensured via an echo that $_session[] gave me Agent912-491). Now the database correctly returns the record again!
So for some reason the $GET["jobnumber"]; statement when set to $jobnumber is failing [even though when it is echoed it returns the correct value that works implicity (and when set it via $s[session]. So there is clearly an issue with a) requesting $_GET["jobnumber"]; b) setting it to the $jobnumber and then c) using that in the WHERE statement. Everything else works as does setting $jobnumber implicitly or via $_session.
I have an incline it might be something to do with santitising the $_GET result before using it. But that really is a guess and even if correct I dont know what exactly to try out.
Help would be really appreciated. Many thanks.

PHP MySQL Negative Value (Balance) Issue

I am developing a desktop software where it charge user per execution the main action. For example say it will charge user 0.1$ for per PDF print.
and my software provide multithreading. .
so, if it run single thread it works fine :)
but the problem is if user run multiple thread at one (say 10/20 threads)
it (php) also continues user to allow the server/execution even balance get below zero..
though my php script check whether balance is positive ..
but after user run multiple threads balance become like -5.95$ or -25.75$ etc
and that is a big security/financial issue..
here is the code I am using:
<?php
$strSQL = "Select * from users where Email = '$strUser'";
$return = mysql_query($strSQL, $strDBConn);
$strDBData = mysql_fetch_array($return, MYSQL_ASSOC);
//checking balance
$strBalance = $strDBData['Balance'];
if($strBalance < 0)
{
// if balance 0 then exit so, my software/thread will not process further
mysql_close($strDBConn);
exit('Balance Exceed');
}
//rest of the codes that realted to service executaion
// code that substract the balnce
$dblCost = 0.25;
$strSQL = "Update users set Balance = Balance - '$dblCost' where Email = '$strUser'";
$return = mysql_query($strSQL, $strDBConn);
//rest finising codes
?>
any help/suggestion would be highly appreciated..
thanks in advance.
best regards
I think, this is a quite similar question:
What is equivalent of the C# lock statement in PHP?
First, try to switch away from the old "mysql" to somethin new, maybe some PDO like DB access ;).
Then, for getting around with multi-thread in php, it can be a good idea, to write a file for every userid (!) and lock this file, when there's a request. When file is locked in another thread, wait for x seconds for the file to be unlocked by the locker-thread. If it is not unlocked within time, something went wrong. When in locked-thread all went good, unlock the file after every operation needed.
Theoraticaly you will be good with then till there's a multi-thread soloution in PHP ;)

mysql plus one a column

i use my own mvc framework.
and post action is :
function post($pid = 0 , $title = '')
{
$pid = $this->input->clean($pid);
$stm =$this->Post->query("UPDATE posts SET `show_count`=show_count+1 WHERE id = $pid");
$stm->execute();
$row = $this->Post->find()->where(array('id'=>$pid))->fetchOne();
$this->layout->set('comments' , $this->comments($pid));
$this->layout->set('row' , $row);
$this->side();
$this->layout->view('post');
echo $this->layout->render($row['title']);
}
i want to when a record fetch from database plus one show_count column .
i use this query :
UPDATE posts SET show_count = show_count + 1 WHERE id = $pid
this right in localhost but in my shared host when run query instead of one pluses ,2 plus show_count column.
how can i solve this problem?
It's working in your localhost but not your internet host. The host is probably doing something behind the scenes that makes it not work. Also, since you don't have access to all the configuration stuff on the host server, you probably won't be able to just fix it.
Simplest fix is to do it in the software layer (assuming $pid is unique).
First get the show_count.
Then:
$oldShowCount = the current show_count
$newShowCount = $oldShowCount + 1
UPDATE posts SET show_count = $newShowCount WHERE id = $pid AND show_count = $oldShowCount
At this point, if no race conditions occurred the row will update (rows update = 1). If a race condition occurred, the update will fail (rows updated = 0).
Then check the # rows updated to verify it worked and repeat until it does.
This is quite common case.
You are running your script twice. Probably because browser is calling it twice. Check your rewrite rules.

How to periodically push data to the user interface in php

i need to implement a simple project using PHP and MySql in which i need to push data to the user's UI when some one else is updating the database, and i need to periodically do this too, so when some one else accessing the same table and modify it, another person who uses the UI can see the updates, sorry if i'm being silly but up to now i'm only aware of saving data to a database and retrieving and showing it to the user(simplest form of data base connection). how can i achieve this in php, please some one help me on this matter, if the answer explains the things in detail it is good, because i'm very novice to this.thanks in advance.
rangana.
If the web page has no data to return, then get the page to wait for a period while polling the database. You must use the sleep statement to avoid maxing out your server.
Warning: Some servers wont let the user open another page while one is in progress, which may cause you problems in some situations. So either dont hold the page open for too long, or maybe try to get the ajax page to use a different session.
// do this when you have put new data in to database
setappdata("lastupdate",microtime(true));
// use this loop to poll for new data
$loop = 0;
$lastupdate=$_SESSION["lastupdate"];
while ($lastupdate==$last=getappdata("lastupdate") and $loop<10) {
$loop++;
usleep(500000); //0.5sec
}
// use a table called appdata to store application data
function getappdata($var) {
$query = "SELECT data FROM appdata WHERE var='$var'";
$res1=mysql_query($query);
if (mysql_numrows($res1)<1) return false;
return mysql_result($res1,0,"data");
}
function setappdata($var,$data) {
$query = "SELECT data FROM appdata WHERE var='$var'";
$res1=mysql_query($query);
if (mysql_numrows($res1)>0) $query = "UPDATE appdata SET data='$data' WHERE var='$var'";
else $query = "INSERT INTO appdata SET var='$var',data='$data'";
return mysql_query($query);
}
These topics may get you started:
http://en.wikipedia.org/wiki/Push_technology
http://en.wikipedia.org/wiki/Reverse_Ajax

Categories