I want that my PHP checks if the time in the mysql db is the same, and if not that it will be changed.
This is what I got:
<?php
$last_time_check=mysqli_query($con,"SELECT `time` FROM `servervars`");
if((time()-$last_time_check) >=1)
{
mysqli_query($con, 'UPDATE `servervars` SET `time`='.$time.' WHERE ID=1');
}
?>
$con is the connection to the DB.
Current value 'time' in servervars: 1412448339
Value 'ID' is 1
I do something wrong, but I just cannot find where it's going wrong.
The Fix
I've removed the variable $last_time_check and only checked if the time could get changed. If this happends then it will send another message to the client.
mysqli_query($con, 'UPDATE `servervars` SET `time` = UNIX_TIMESTAMP() WHERE ID = 1 AND UNIX_TIMESTAMP() - `time` >= 1');
if ($con->affected_rows)
{
// at least 1 second has elapsed, do stuff
}
MySQL has an equivalent to time(), its the function UNIX_TIMESTAMP(). Differently though, it can take a DATETIME as parameter to convert it into UNIX time, but when used without parameters its the same as UNIX_TIMESTAMP(NOW()).
UPDATE servervars SET time = UNIX_TIMESTAMP() WHERE ID = 1
Update
Ok so about the other issues. You are doing it all wrong. mysqli_query does not return the value directly. To fetch the value of time from the database, you need 3 steps:
$result = $con->query('SELECT `time` FROM `servervars` WHERE ID = 1'); // fetch result set
$row = $result->fetch_row(); // fetch a row from the result set, as an array
$last = $row[0]; // get the first element from the row you just fetched
Notice $con->query() can fail if theres a problem with the connection, the database, the table, or the query syntax itself, and $result->fetch_row() can fail if there are no results for the query. You should validate them before proceeding to the next step.
Alternatively, you can do this:
$con->query('UPDATE `servervars` SET `time` = UNIX_TIMESTAMP() WHERE ID = 1 AND UNIX_TIMESTAMP() - `time` >= 1');
if ($con->affected_rows)
{
// at least 1 second has elapsed, do stuff
}
This way we shortened your solution to a single query, that updates the field if necessary and report back that it happened or not..
Related
I have problems comparing dates between a date created with new dateTime () in php, and a date taken from a DATETIME field of a Mysql table.
With the following code, save a date in a DATETIME field of a MySQL table:
$now = new DateTime();
$update = $mysqli->query('INSERT INTO bonus (idplayer,lastlogin) VALUES ("'.$_GET["idplayer"].'","'.$now.'")');
Then I would like to retrieve the date from the tables and compare it with a date created using the php code:
$resetTime = new DateTime();
date_time_set($resetTime, 12, 00, 00);
$lastLogin = $mysqli->query('SELECT lastlogin FROM bonus WHERE idplayer = "'.$_GET["idgiocatore"].'"');
if ($resetTime < $lastLogin) {
echo "OK!<br>";
}
Using this code I can't comparate the dates because I get an error (I can't even do an echo of the date retrieved from the table).
Can anyone tell me where I'm wrong and how can I solve the problem?
Try this
$resetTime = (new DateTime)->format('Y-m-d 12:00:00'); //need it as a string
//$resetTime = date('Y-m-d 12:00:00'); //-- this is fine too
$stmt = $mysqli->parpare('SELECT lastlogin FROM bonus WHERE idplayer = ?');
$stmt->bind_param("s", .$_GET["idplayer"]);
$stmt->execute();
list($lastLogin) = $stmt->get_result()->fetch_array();
if ($resetTime < $lastLogin) {
echo "OK!<br>";
}
Basically your comparing the query result set, to your timestamp, instead of the value of the first column of the first row. Consider you code:
$lastLogin = $mysqli->query('SELECT lastlogin FROM bonus WHERE idplayer = "'.$_GET["idgiocatore"].'"');
if ($resetTime < $lastLogin) {
mysqli::query
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
https://www.php.net/manual/en/mysqli.query.php
Your also full of SQL Injection errors, an input such as this:
$_GET["idgiocatore"] = '" OR 1 ORDER BY lastlogin DESC LIMIT 1 --'
Will turn your query into this
'SELECT lastlogin FROM bonus WHERE idplayer = "" OR 1 ORDER BY lastlogin DESC LIMIT 1 -- "'
Everything after the -- is a comment so we can ignore that ending ". This avoids creating a syntax error, and is a very common tactic (nothing new).
This will select all records from the DB because Anything plus OR 1 is always true, then it will sort them by your lastlogin value DESC so the highest value is first and Limit to 1 return row, well just because I can. Basically this will satisfy your if condition if ($resetTime < $lastLogin) Which I guess is a "good thing" (well for me, the haxor).
Essentially this is because you are just pasting user input right into the SQL, so it becomes part of the command if formulated correctly (not a good thing for you).
Anyway Hope it helps you.
*PS it's been an age (like 6 years) sense I used MySqli (normally I use PDO) so forgive me any errors there, most of that came from a basic tutorial over at W3Schools
One last thing instead of setting the time, consider removing it altogether with the MySql DATE() function:
$resetTime = (new DateTime)->format('Y-m-d');
//...
$stmt = $mysqli->parpare('SELECT DATE(lastlogin) FROM bonus WHERE idplayer = ?');
I have a field on my website, which updates a value in my mysql database. I want to make it so the user can only update the value every 3 days. How would I go about doing this?
Here is the code that I have written so far:
<?php
if(isset($_POST['Update'])){
$UpdateHWID = $_POST['HWID'];
$sql = $con->query("UPDATE users SET HWID = '{$UpdateHWID}' where UserID = $User");
echo "HWID Updated Successfully!";
}
?>
Use a last updated field in mysql (date and time of last update), and check it before making the update. If satisfies your condition then commit the update and also update that time field, if not show error to the user.
Create new row into db (last_update) type= data
//return to sql last_update (select db ...)
$current_Data = date ('Y-m-d');
$current_Data_time = strtotime ($current_Data); //convert data to time
$last_update_p3 = strtotime ("+3day", strtotime($last_update));
$last_update_p3 = strtotime ($last_update_p3);//convert data to time
if($current_Data_time <=$last_update_p3)
{
$sql = $con->query("UPDATE users SET HWID = '{$UpdateHWID}' , last_update='{$current_Data}' where UserID = $User");
//update last data with current date
}
else
{
//It has not gone three days
}
According to Pinx0, if you add a new column to your users table which contains the date of the last update, then you can create a condition. For example:
ALTER TABLE `users`
ADD `lastUpdated` DATE NOT NULL;
Now you can add a condition to your existing query something like this:
UPDATE `users`
SET `HWID` = '{$UpdateHWID}',
`lastUpdated` = NOW()
WHERE `UserID` = $User AND 2 < DATEDIFF(CURDATE(),`lastUpdated`);
You can easily do that, using the DATEDIFF method.
It will be my first comment. so, Let me know if I have written
something incorrectly here.
$currentDate = date('Y-m-d');
$query = "SELECT DATEDIFF($currentDate,*Last_update_date_row_name*) as diff FROM *TABLE_NAME* WHERE user_id=Current_User_Id";
$result = mysqli_query($conn,$query);
if($result!=false){
//compare the diff with your desire number
// then you can hide or disable the button or show error
}
As the title says.
From the database, in the resultset, I want those rows where the date and time (schedule column) are already passed.
In the database I have
On the PHP page I have:
$now = time();
$result = $mysqli->query("SELECT * FROM schedules WHERE $now >= UNIX_TIMESTAMP(schedule)");
However, if I test this on 2015-09-19 at 18:50:00, I get no results at all, while instead I should only get the row with ID 39.
As much as I know I am comparing two valid timestamps - the one generated by time() and the one converted from the database with UNIX_TIMESTAMP() - so what isn't working?
EDIT: I already tried to do
$result = $mysqli->query("SELECT * FROM schedules WHERE NOW() >= schedule");
But with no luck. I am getting the results with
while ($row = $result->fetch_assoc()) {
$id = $row['ID'];
echo $id;
}
Use now() to select rows where schedule is in the past
SELECT * FROM schedules WHERE now() > schedule
They are different because,
php time is based on the php timezone setting (inside php.ini).
database time is based on your system time (unless you set it).
I'm trying to update my first row in my database. I use the Limit 1 to only update the first row but nothing is happening. There are definitely matching rows but nothing changes in the database.
Here is the code:
foreach ($player_fromsite as $match_player_in_game) {
//$querytwo = 'INSERT INTO `'.$tablename.'` '.' (`'.$match_player_in_game.'`) '.'VALUES'.'("' . 'yes' . '")';
$querytwo = 'UPDATE '.$tablename.' SET `'.$match_player_in_game.'` = "'.'yes'.'" WHERE `'.$match_player_in_game.'` = "'.'NULL'.'" LIMIT 1';
$querythree = 'UPDATE '.$tablename.' SET `'.$match_player_in_game.'` = "'.'yes'.'" WHERE `'.$match_player_in_game.'` = "'.'NULL'.'" LIMIT 1';
for($a=0;$a<11;$a++){
if($match_player_in_game == $home_players[$a]){
// Insert a row of information into the table "example"
mysql_query($querytwo) or die(mysql_error());
}else{
mysql_query($querythree) or die(mysql_error());
}
}
}
Is the query correct?
In MySQL use IS NULL to compare with NULL.
For example: "UPDATE table SET field = 'yes' WHERE field IS NULL"
NULL isn't a string, so you shouldn't be using = 'NULL', unless you actually set it to that string value. Use IS NULL instead.
You need to define "first row". First row based on an autoincrementing id value? First based on a timestamp date? You need to specify this as MySQL has no concept of "first row".
For example, if you do something like this in MySQL:
SELECT * FROM table LIMIT 1
You are not guaranteed to get the same record back each time.
Most likely you will need to specify an ORDER BY condition on a key column, as without it, you have no guarantee of which row your LIMIT 1 will apply to. I really can't think of a case where one might use LIMIT without an ORDER BY clause, as the two really go hand in hand.
So your query should look like:
UPDATE table
SET field = 'yes'
WHERE field IS NULL
ORDER BY some_key_field ASC
LIMIT 1
Note that even this query would not update the same row every time. It would update the first record (as specified by ORDER BY) that has a NULL value for the specified field. So if you ran this query 10 times, it would change 10 different records (assuming there are that many records with NULL values).
Using the code below, I'm having trouble checking whether a specified date exists in a MySQL 'date' column.
$data = array(1367971200);
$s=$dbh->prepare("
SELECT DISTINCT
`date`
FROM
`report_coa_bal_hist`
WHERE
UNIX_TIMESTAMP(`date`) = ?
");
if ($s->execute($data)) {
if ($s['date'] == null) {
return false;
}
return true;
}
It's returning false, despite the fact that I can see the date '2013-05-08' displayed in phpMyAdmin.
The table itself contains 70+ entries for that date. It always will do, if it contains any at all, but I just want to know whether it exists or not at this stage.
The date field is a MySQL 'date' type. I'm suspecting that the bug is in my structuring of the PDO calling of the query.
UPDATE
Updated $r['date'] to `$s['date']. I suspect that I still have an issue with the structure of that, but probably need to fix the query so that it gives us results before focusing on this.
Also tried running the query against the database directly and got an empty resultset, despite being able to see that the target date exists. Still baffled!
Try this
$data = array(1367971200);
$s=$dbh->prepare("
SELECT COUNT(`date`) as c_date
FROM
`report_coa_bal_hist`
WHERE
UNIX_TIMESTAMP(`date`) = ?");
if ($s->execute($data)) {
$result = $s->fetch(PDO::FETCH_ASSOC);
if ($result['c_date'] > 0) {
return false;
}
return true;
}
You can't select a whole day with UNIX timestamps because of their more accurate nature (i.e. seconds), you would need the textual version:
$data = array(date('Y-m-d', 1367971200));
$stmt = $dbh->prepare("SELECT COUNT(*)
FROM `report_coa_bal_hist`
WHERE `date` = ?
");
$stmt->execute($data);
$count = current($stmt->fetchAll(PDO::FETCH_COLUMN, 0));
return $count > 0;
Take note of any timezone differences between the server that runs your script and the database server itself.
there are many flaws with your code, not one:
format of the value you are checking
way you are checking in SQL
the way you are getting result
So, the code have to be
$data = array('2013-05-07');
$sql = "SELECT 1 FROM report_coa_bal_hist WHERE `date` = ? LIMIT 1";
$stm = $dbh->prepare($sql);
$stm->execute($data);
return $stm->fetchColumn();