Why the script saves all the time the same data? - php

I have a problem with my php Script that the system runs every minute.
My php-script is this:
<?php
$y = date("Y", time());
$m = date("m", time());
$d = date("d", time());
$h = date("H", time());
mysql_connect("localhost", "root", "");
mysql_select_db("dashboard");
$check_date = mysql_query("SELECT year,month,day FROM serverstats WHERE year='".$y."' && month='".$m."' && day='".$d."'");
if(mysql_num_rows($check_date)==0) {
mysql_query("INSERT INTO serverstats (year,month,day,h01,h02,h03,h04,h05,h06,h07,h08,h09,h10,h11,h12,h13,h14,h15,h16,h17,h18,h19,h20,h21,h22,h23,h24)
VALUES (
'".$y."', '".$m."', '".$d."', NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL
);
") or die(mysql_error());
} else {
$load = file_get_contents("/proc/loadavg");
$load = explode( ' ', $load );
$total_load = $load[0] + $load[1] + $load[2];
$last_load = mysql_query("SELECT h".$h." FROM serverstats");
$daten = mysql_fetch_array($last_load);
$total = $daten["h".$h.""]+$total_load;
mysql_query("UPDATE serverstats SET h".$h."='".$total."'");
mysql_query("UPDATE serverstats SET ts ='".time()."'");
}
?>
And the database looks like this:
The Timestamp(ts) and the other values are the same, what did I make wrong?

You are missing where condition in update
UPDATE serverstats SET ts ='".time()."'"
While updating the database it should have where clause .. your sql should be something like\
UPDATE serverstats SET ts ='".time()."' Where = 'your condition'"
If you miss where in update clause .. then all records will get updated ..
NOTE please switch to mysqli_* or PDO . mysql_* are no longer officially maintained.

I assume, the ts is not an "on update CURRENT_TIMESTAMP" field. Having this would make it easier, leaving the ts stuff to the DB.
BUT:
these two statements
mysql_query("UPDATE serverstats SET h".$h."='".$total."'");
mysql_query("UPDATE serverstats SET ts ='".time()."'");
Will always update all records in the table - missing where clause.
Try this:
mysql_query("UPDATE serverstats SET h".$h."='".$total."', ts ='".time()."' ".
" WHERE year='".$y."' && month='".$m."'` && day='".$d."'");
and obviously
$last_load = mysql_query("SELECT h".$h." FROM serverstats " .
" WHERE year='".$y."' && month='".$m."'` && day='".$d."'");
since otherwise this is reading the entire table and your taking just an arbitrary first row.

It seems I don't have enough rep to leave comments but as an aside, you're using:
$h = date("H", time());
Which is in the form of 00 to 23 but the table columns are 01 - 24.
This may become an issue for example at 00:
$last_load = mysql_query("SELECT h".$h." FROM serverstats");
...

Related

PHP MYSQL Update multiple fields including DATETIME field

I can update the field 'delivered' from 0 to 1 no problem but when I try to update 'delivered_time' nothing happens in the database. This may be to do with the way I am writing the code but If anybody could help I would really appreciate it, thanks!
if (isset($_POST['delivered']) === false) {
mysql_query("UPDATE `listings` SET `delivered_time` = '{$date->format('Y-m-d H:i:s')}' AND `delivered` = 1 WHERE `order_id` = $order_id");
}
I have also tried this but this did not work either
if (isset($_POST['delivered']) === false) {
mysql_query("UPDATE `listings` SET `delivered_time` = NOW() AND `delivered` = 1 WHERE `order_id` = $order_id");
}
My MYSQL database is set to have 'delivered' defined to 0 and is stored as an INT value. The 'delivered_time' field is stored as a DATETIME value in the database.
, not AND as the field separator; AND is used in WHERE clauses
UPDATE `listings`
SET `delivered_time` = '{$date->format('Y-m-d H:i:s')}',
`delivered` = 1
WHERE `order_id` = $order_id
Try this code
<?php
if (isset($_POST['delivered']) === false) {
mysql_query("UPDATE `listings` SET `delivered_time` = NOW(),`delivered` = 1 WHERE `order_id` = ".$order_id);
}
?>

PHP PDO why select only first row in Database table?

I am PDO newbie, and i can't figure why i can select only first row in Table on database.
This is my DataBase TABLE :
Column Type Null Default Comments
id int(11) No
cred varchar(20) No
tok char(40) No
ptok char(40) No
t char(128) No
expires varchar(26) No
Indexes
Keyname Type Unique Packed Column Cardinality Collation Null Comment
PRIMARY BTREE Yes No id 1 A No
ptok BTREE Yes No ptok 1 A No
And this is my SELECT (find) function :
public function findTriplet($credential,$token, $persistentToken) {
$sql = "SELECT IF(SHA1(?) = {$this->tokenColumn}, 1, -1) AS token_match " .
"FROM {$this->tableName} WHERE {$this->credentialColumn} = ? " .
"AND {$this->persistentTokenColumn} = SHA1(?) LIMIT 1 ";
$query = $this->connection->prepare($sql);
$query->execute(array($token, $credential, $persistentToken));
$result = $query->fetchColumn();
if(!$result) {
return self::TRIPLET_NOT_FOUND;
}
elseif ($result == 1) {
return self::TRIPLET_FOUND;
}
else {
return self::TRIPLET_INVALID;
}
}
Anyway i tryed to search for answer , but i dont know PDO so good so its not matter..
I tryed play with that , no succses..
Anyone know what is my problem in the findTriplet function and what i am doing wrong ?
It will only select first database row so if i have more then 1 row's it will return false.
Thanks allot.
Remove "LIMIT 1" from your variable and see if results change:
$sql = "SELECT IF(SHA1(?) = {$this->tokenColumn}, 1, -1) AS token_match " .
"FROM {$this->tableName} WHERE {$this->credentialColumn} = ? " .
"AND {$this->persistentTokenColumn} = SHA1(?) LIMIT 1 ";
Becomes:
$sql = "SELECT IF(SHA1(?) = {$this->tokenColumn}, 1, -1) AS token_match " .
"FROM {$this->tableName} WHERE {$this->credentialColumn} = ? " .
"AND {$this->persistentTokenColumn} = SHA1(?)";
It appears you are retrieving a match, so you are seeing a SINGLE result. I'm not sure of the application, but you might want to keep a Limit in the SQL statement. Removing the LIMIT will at least be a good testing point.

Update Query not updating field in table

I am currently struggling with the following :
$res = $db->uniquequery("SELECT distinct won_current,ctt,darkmatter FROM ".USERS." WHERE `id` = '".$USER['id']."'");
$checkwon = $res['won_current'];
$ct=$res['ctt'];
$dm=$res['darkmatter'];
These appear to be working. Now...
$dmgift=0;
while($checkwon>=1000)
{
$ct=$ct+1;
//incrementing $ct doesnt seem to work in the loop but it works fine outside it
$checkwon=$checkwon-1000;
//threshold ranges and setting of dmgift.
switch($ct){
case $ct=1 : $dmgift=25000;break;
case $ct>=5 && $ct<10: $dmgift=50000;break;
case $ct>=10 && $ct<15: $dmgift=75000;break;
case $ct>=15 && $ct<20: $dmgift=100000;break;
case $ct>=20 : $dmgift=150000;break;
}
$dm=$dm+$dmgift;
//$db->query("UPDATE ".USERS." SET won_current=$checkwon,ctt=$checkthreshold,darkmatter=$dm WHERE `id` = ".$USER['id'].";");
$db->query("UPDATE ".USERS." SET won_current=$checkwon WHERE `id` = ".$USER['id'].";");
$db->query("UPDATE ".USERS." SET ctt='$ct' WHERE `id` = ".$USER['id'].";"); // this update query is not passing.db field remains the same
$db->query("UPDATE ".USERS." SET darkmatter=$dm WHERE `id` = ".$USER['id'].";");
}
Kindly advise...the other 2 update queries are passing well...if you notice above the 3 updates I had a full query commented in...split it to see what is not working in update...
I did echo and vardump...outside the loop they gave me the correct values...BUT inside the loop they have me 11111 instead of 5...for example...not sure what I'm doing wrong....I'm very new to php ( 2 days ? ) and would appreciate a solution...
The problem is with the switch.
switch($ct){
case $ct=1 : $dmgift=25000;break;
...
}
The first case changes $ct to 1, so its value is always 1 in the SQL query so it looks like the query doesn't work.
In any case switch doesn't work like that, you need separate if phrases:
if( $ct == 1 ) {
$dmgift=25000
}
else if( $ct>=5 && $ct<10 ) {
$dmgift=50000;
}
else if( $ct>=10 && $ct<15 ) {
$dmgift=75000;
}
else if( $ct>=15 && $ct<20 ) {
$dmgift=100000;
}
else if( $ct>=20 ) {
$dmgift=150000;
}
Also note that you don't have cases for $ct between 2 and 4.
Check for $ct value.
If $checkwon is not greater than or equal to 1000, $ct value will remain the same db value
$db->query("UPDATE ".USERS." SET ctt='" . $ct . "' WHERE `id` = ".$USER['id'].";");
Change your update query
$db->query("UPDATE ".USERS." SET won_current = '".$checkwon."' WHERE `id` = '".$USER['id']."'");
$db->query("UPDATE ".USERS." SET ctt = '".$ct."' WHERE `id` = '".$USER['id']."'");
$db->query("UPDATE ".USERS." SET darkmatter = '".$dm."' WHERE `id` = '".$USER['id']."'");
Remove ";" semicolon from here
use single quotes for values of MySQL
$db->query("UPDATE ".USERS." SET won_current='$checkwon' WHERE id = '".$USER['id']."'");

PHP / MYSQL Insert on duplicate key update if CURDATE() match otherwise make new entry

I am facing a problem in making a program with mysql and php...
See i want to save my search queries into the database,,
See this example
Stackoverflow searched = > 20 times on date = > 2013-04-26
Stackoverflow searched = > 10 times on date = > 2013-04-27
Stackoverflow searched = > 50 times on date = > 2013-04-28
Formatting does not matter..Actually i want to save my search queries if the date is changed..
If date got matched so should update times + 1
See this code,,
<?php
$keyword = null;
$date = null;
if (!empty($_GET['s'])) {
$keyword = stripslashes($_GET['s']);
$date = date("Y-m-d");
try {
$objDb = new PDO('mysql:dbname=search;charset=UTF-8', 'root', '');
$check = "SELECT *
FROM `search1`
WHERE `keyword` = '$keyword%'
AND `date` = CURDATE() ";
if (!empty($check))
{
$sql ="UPDATE `search1`
SET `times` = `times` + 1
WHERE `keyword` = '$keyword%'
AND `date` = CURDATE()";
}
else
{
$sql = "INSERT INTO `search1` (`keyword`, `date`) VALUES (:keyword, :date)";
$statement = $objDb->prepare($sql);
$statement->execute(array(':keyword' => $keyword, ':date' => $date));
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
It is not working.. Something is wrong.. Someone can tell me what is wrong.
I can not use primary key.
you can set a unique index on the field date and keyword
ALTER TABLE `search1` ADD UNIQUE (
`keyword` ,
`date`
);
edit: looks like the OP has got it now, but just for completeness, the above query you just run once to add a unique index to the table - note that it won't work if you have rows that have the same values for keyword and date; if you get a 'duplicate value' error you will have to remove rows until the values are unique before trying again.
then the query
INSERT INTO `search1` (`keyword`, `date`, `times`) VALUES (:keyword, :date, 1) ON DUPLICATE KEY UPDATE `times` = `times` + 1
should do the trick :)

How can I update with a NULL value

I am trying to update a mysql table. If there is no value I want null but I'm getting 0 if $ODate is empty. Actually I'm getting 0000-00-00. What I need to do is get rid of the ' ' then it will take the NULL value but then it doesn't work if there is a valid date value.
if (($_POST['OrderDate'])==null){$ODate='NULL';}else {$ODate=$_POST['OrderDate'];}
//this will update a valid date but returns 0000-00-00 if set to NULL
"UPDATE tblLoads SET OrderDate = '$ODate',
//this will update NULL but returns 0000-00-00 if a valid date
"UPDATE tblLoads SET OrderDate = $ODate,
$ODate = empty($_POST['OrderDate']) ? "NULL" : "'$_POST[OrderDate]'";
$query = "UPDATE tblLoads SET OrderDate = $ODate, ...";
You could have an if else, checking for if $ODate is NULL, if it is then don't use the quotes, if it isn't null, then use the quotes.
e.g.,
if (!is_null($ODate)) {
$ODate = "'" . $ODate . "'";
}
"UPDATE tblLoads SET OrderDate = $ODate,

Categories