I am working on a project in which the dates in the sql table needs to be checked with current date. If the ticket goes past the current date, then the status of ticket go from Active to Expired.
I am not good at php. This is what I came up with. I wrote this function at top of the page so that each time the page loads, it checks for the date and compares. date format is yyyy-mm-dd.
What am I doing wrong. Can anyone please help me out?
$result= "SELECT date, status FROM TABLE1";
while($row = sqlsrv_fetch_array($result)){
if(strtotime($row['date']) > strtotime(date('Y-m-d'))){
$updatequery = " UPDATE TABLE1 SET $row[status] = 'Expired' ";
}}
I would advise using the PHP DateTime class it has the date diff function so you could implement like this
$today = new DateTime('today');
$expires = new DateTime($datefromdb);
$diff = $today->diff($expires);
if($diff < 1)
{
$updatequery = " UPDATE TABLE1 SET $row[status] = 'Expired' ";
}
You can use
$result= "SELECT UNIX_TIMESTAMP(date) AS unixdate, status FROM TABLE1";
and then compare
if ($row['unixdate']) > strtotime(date('Y-m-d')))
Your sql database may be on a server whose time is different from the time on the machine where you are running the code, so I would recommend doing the check and update all on the sql server side.
(Disclaimer: I use mysql, so that's how I've written my answer. I assume you can translate to whatever sql database you use)
I would recommend using MySql's date functions, which you can see here.
UPDATE TABLE1 SET status='Expired' WHERE DATEDIFF(CURDATE(), date) < 0
Below code working for me, just a single line of update query will updated less than of current date
UPDATE TABLE_NAME SET status='expired' WHERE DATEDIFF(date, CURDATE()) < 0
Thank.
Related
I have been trying to pull records based on a specified date. In the DB I have a column where I store unix timestamps. The user has the option to select records based on a date. The user inputs: 08/08/2016 (for example)
How would I write my SQL statement to handle this?
$query .= "`".$o."` = '".date("Y-m-d",strtotime($v))."' AND ";
Here we see the line where part of the SQL statement is built, because more than one column could be targeted by the user during their search request.
Somehow I need to be able to turn $o (which is a column storing unix timestamps) into the Y-m-d format for comparison, as shown above and make this work in an SQL statement.
Any help would be appreciated.
EDIT
Here is what worked for me:
$query .= "".$o.">= '".strtotime($v)."' AND".$o."< '".(strtotime($v)+(24*60*60))."' AND ";
You can do something like:
"WHERE DATE(`$o`) = '".date("Y-m-d",strtotime($v))."'"
However this won't use indexes, so if you have a large table it will be slower. If you want to be able to use indexes you can do:
"WHERE `$o` >= ".date("Y-m-d",strtotime($v))."
AND `$o` < ".date("Y-m-d",strtotime($v))." + INTERVAL 1 DAY"
You can also try this approach and use UNIX_TIMESTAMP on MySQL.
$v = '2016-08-04';
$query .= "'".$o."' = UNIX_TIMESTAMP('$v') AND ";
This all worked before I added the section to update "last_update".
if((time() - $last_update) > 7200){
$sql = $dbh->prepare("UPDATE item_list SET quantity=:quantity, price=:price, last_update=:now WHERE item_name=:itemname");
$sql->bindParam(':quantity', $json->volume);
$sql->bindParam(':price', $json->lowest_price);
$sql->bindParam(':itemname', $row['Item_Name']);
$sql->bindParam(':now', "NOW()"); //This doesn't work
$sql->execute();
}
When this is called I want to make last_update the date and time now. In the database it is currently a DATETIME, and when I last_update I origianly set them to NOW();
Doing this I get the error Fatal error: Cannot pass parameter 2 by reference in.... Directory
I know it expects a variable, I'm not sure how to fix it though. I tried setting
$now = "NOW()";
$sql->bindParam(':now', $now);
No prevail. Any help?
Why you need to bind, just put NOW() directly
$sql = $dbh->prepare("UPDATE item_list SET quantity=:quantity, price=:price, last_update=now() WHERE item_name=:itemname");
If your last_update column is looking for a UNIX timestamp, then do :
$now = time();
$sql->bindParam(':now', $now);
If it's after a different time format, use date(), and the relevant formatting it has to set the date and time
You can keep your bind query as it is & remove the last_update column from the query.
Since you are updating other things in the record via another query, then you can set the default value of the field last_update to CURRENT_TIMESTAMP & set it's attribute as ON UPDATE CURRENT_TIMESTAMP. That will ensure it automatically updates itself with the current time now() whenever that record is updated.
It wouldn't be the best thing to remove bind() as you rightly said to prevent SQL injection attempts.
I have a php that extracts information from a mysql database just fine, however when I tried to add the functionality to check for data depending on an interval I am not getting any data from the database, just replies with an empty result. When I run it in Phpmyadmin it works just fine. Here's the code:
$result = mysql_query("
SELECT * FROM SensorLog
WHERE (SensorTag='$requestedSensor' and TimeEntered<'$end'
and TimeEntered>'$start');
") or die(mysql_error());
start and end are of the form: 2014-01-22 15:36:37 just like my timestamped column in the database.
What am I doing wrong here? I assume something is wrong with the query but I can't figure out what.
Same can be achieved using BETWEEN clause as follows:
$result = mysql_query("SELECT * FROM SensorLog
WHERE (SensorTag='$requestedSensor' and TimeEntered BETWEEN '$end' AND '$start')") or die(mysql_error());
If date start and date end have the same value, the query should be TimeEntered >= $start and TimeEntered <= $end
I'm creating a login script. In this script, I would like to limit the users login attempts, but only for an hour. After an hour, they can try again, several times, before waiting another hour. In my database, I have ID, IP address and DateTime fields.
I have Google'd it, and didn't found a solution. However, from searching on the TIMEDIFF, there was quite a lot information. From that, I've made the query and script below. The problem is, it doesn't work. Could you help me to make it working?
$query = "SELECT * FROM `log` WHERE `ip` = '".$ip."' AND TIMEDIFF('".date('Y-m-d H:i:s')."',`datetime`) > '24:00:00'";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
if($rows >= $this->maxAttempts)
{
...
}
Thanks in advance for all your help.
Consider using simple math and the INTERVAL syntax instead:
SELECT *
FROM log
WHERE ip = ?
AND (datetime + INTERVAL 1 HOUR) > NOW()
I've built a small application which has User Management, a frontend console to enter data and a backend console to control parts of the frontend. The frontend adds rows to a MySQL database which are timestamped. The backend needs to be able to select rows from the database between X and Y dates.
Everything works so far, except the date part which I'm really struggling with.
The frontend SQL input looks like this (simplified with spurious code removed):
$date = time();
$top_level_category = $_POST['top_level_category'];
$sub_level_category = $_POST['sub_level_category'];
$company = $_POST['company'];
$agent_name = $_POST['agent_name'];
$ticket_id = $_POST['ticket_id'];
$sql = "INSERT INTO dacc_data ("
. "id, top_level_category, sub_level_category, "
. "agent_name, date, ticket_id, company"
. ") VALUES ("
. "NULL, '$top_level_category', '$sub_level_category', "
. "'$agent_name', FROM_UNIXTIME('$date'), '$ticket_id', '$company'"
. ")"
;
$result = mysql_query($sql) or die (mysql_error());
That seems to work ok, the timestamp is being picked up and added to a DATETIME column in my table. It displays as dd/mm/yyyy hh:mm:ss within the database.
So ... my first question is - is this the right way to do it?
The second question being, what sort of SQL statement would I need to pull out an array of rows between X and Y date.
Apologies if this is rambling a bit, hope it's clear but if you need more information let me know.
MySQL datetime should be formatted with dashes:
YYYY-MM-DD HH:MM:SS
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
Then you can query for date ranges a couple of ways:
select *
from table
where date >= '[start date]' and date <= '[end date]';
or
select *
from table
where date between '[start date]' and '[end date]';
where "table" is the name of your database table and "date" is the name of your datetime field.
You are correct. I can confirm that the Database has "YYYY-MM-DD HH:MM:SS" - I am using SQLWave editor for browsing the DB quickly, it auto-formats the DATETIME column.
// Initial questions still stand :)
Or not, just noticed you updated the answer - thank you very much! I had actually tried that very same query several times to no avail, mainly because my WHERE was specifying the date format incorrectly. Misled by SQLWave :(
Back to using command line from now on !!!
"what sort of SQL statement would I need to pull out an array of rows between X and Y date?"
SELECT * FROM `dacc_data` where `date` between "2008-11-01" and "2008-12-01"