I have a PHP script which creates a new order and inserts the time NOW + 15 minutes into the database.
After 15 minutes have expired the user cannot access the order page.
On the admin panel I only want to show records that have not expired, so my question is what select statement would I use to do this, and which would be the most efficent?
SELECT * FROM `orders` WHERE datenow > date
The "date" is the date of the order + 15 minutes
P.S.
Aternativly, is there any way to do this using PHP so I don't have to put too much stress on the database?
Many Thanks!
Given that you want records that have not yet expired, you want all records where date is greater than NOW().
SELECT
*
FROM
`orders`
WHERE
`date` > NOW()
As the comments mentioned, it is usually better to handle this on the database side; rather than transfer (assuming you have split database and web servers) the entire data set to filter it in the application code.
The other benefit of having all the datetime functions be on the same server (in the database in this case), is that especially on some shared hosting environments, the timezone for the database cannot be changed. Therefore, you want the time comparisons to occur in the same timezone.
Related
I want to use the following code to SELECT data older then 1 minute.
SELECT * FROM `auth_temp` WHERE date > (NOW() - INTERVAL 1 MINUTE)
But it didn't work. Then I checked some other topics and one person talked about the server time, I just asked my host and he said the server time is: 15:30
When at my place and the logs in MySQL it is 21:30, aka 6 hours later.
Anyone how I should asjust my code to that?
Thank you all!
You are hitting a timezone issue. Most servers run on UTC. If you have a TIMESTAMP as the field type, MySQL will convert the time from server time to UTC and back. You can adjust what MySQL considers server time using SET time_zone = timezone; (Docs). If you actually care about timezones it is advisable to just use UTC and convert in your application.
Your current SQL statement will only select data newer than 1 minute. Change it to:
SELECT * FROM auth_temp WHERE date < (NOW() - INTERVAL 1 MINUTE)
This will select data that is older than one minute. If you are using NOW() for setting the date column when you are inserting the row then that small fix should do it even if the time zones are different between your application and database layer. If you are setting the date column from your application layer you will have syncing issues if the time zone is set differently than the database layer.
It sounds like the MySQL server is either running in a different time zone or running on Universal Time (UTC) which is common. Running MySQL on UTC time is a good way to deal with users in multiple time zones. In your code, you should be able to synchronize the time zones in use on the database and application layers if it's set to UTC time easily. If it's set to a different time zone, it should be possible as well but not recommended.
I am working on a PHP and MySQL based application in which I am processing mysql data tables for one week data at a time. All my PHP scripts will run in a particular sequence and process the data in all tables (upto 15 tables) for given week.
Presently I have written the date filter in WHERE clause and application is working fine.
IS there any way by which I can set the week's date range at one place and all the queries are fired in all the tables with given date range.
I want this bcoz my application processes are growing and its hard to manage 20+ pages and 50+ queries written in it.
I am using command line PHP.
Please suggest the technique if any.
Thanks
You could use $_SESSION...
$sql = $db->query("SELECT * FROM table WHERE date BETWEEN '". $_SESSION['range']['from'] ."' AND '". $_SESSION['range']['to'] ."'");
... which will persist for the browser session.
SELECT stuff from your_table
WHERE your_date_field > DATE_ADD(CURDATE(), INTERVAL - 7 DAY);
Run that once a week to get last 7 days, then hack it around to get the exact results you want.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
I am trying to make a PHP chat script and I want to make sure it doesn't display any entries older than 1 minute. The database contains a timestamp on each row called timestamp.
How can I do this?
SQL
SELECT *
FROM tablename
WHERE timestamp > TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MINUTE))
It's been a while since I've used that particular function, so I might be a bit off but it's close.
JavaScript
It sounds like you might want to actively hide old messages. In that case you need to include the timestamp meta-data so you can filter it using JavaScript.
I'm trying to create a computer reservation system, where user chooses a computer and select the time how long he will be using this PC. In that time other persons can't reserve this pc, I need to find a solution, how to automaticaly delete all rows containing reserved pc's after their time expires. Thank you for the advice.
The common way to handle this is to store an expires_at timestamp on the reservation row. Then your query to find any "open" reservations would have WHERE 'expires_at' < NOW() or something similar.
This is an untested answer, that may only be a suggestion, but I just started looking at these, so am interested in feedback as well. i'm still working through possibilities and drawbacks, but it might well suit your need.
Take a look at MySQL Events, an article about it is here, and official syntax at Mysql Docs.
Per the article:
An event is similar to a trigger. However, rather than running in
response to a data change, events can be scheduled to run any number
of times during a specific period. In effect, it’s a database-only
cron job.
Pondering this, I'd envision a procedure that deleted anything >1hr (if that's the expiration). This procedure would be TRIGGERED on new inserts to get rid of anything expired at that moment, but also in an event to run every 15 minutes or so so that automatic deletes by the trigger aren't dependant on somebody else adding a reservation to trigger that procedure.
If your server is linux, you can use cron jobs to check once a day every reservation dates. If these dates have expired .. modified field reserves to be available.
Normally I would do it this way:
when storing a reservation, store date_from and date_to both of datatype DATETIME
when checking if there is a computer free check for all computers and filter with WHERE '{$my_date}' >= date_to AND '{$my_date}' <= date_from - by this You should be able to get all the PCs that are not reserved within a certain time...
To be complete in the solution, you need to run a CRON job which calls a query to remove all reservations that have a reservation_time + (15 * 60) < unix_timestamp().
I am assuming you have a time that the reservation was placed or started and are using UNIX/Epoch Timestamps.
Instead of doing a expires_now, if you know it will always be a fixed interval ie 15 minutes, you can do:
DELETE FROM reservations WHERE reservation_time + (15 * 60) < unix_timestamp()
Something you could look into is managing cron job's from PHP, http://www.highonphp.com/cron-job-manager.
The above script will, when a reservation is created, insert an entry into /etc/cron.d/ and you could configure it to run at the expected reservation endtime. Then inside the php file which would be executed, you could do:
DELETE FROM reservations WHERE id = :id
I have a mysql database, or more specific, a mysql table which I store IP adresses in.
This is because I limit the nr of messages being sent from my website.
I simply check if the IP is in the table, and if it is, I tell the user to "slow down".
Is there any way to make this MySql table only store a row (a record) for x minutes?
Other solutions are also appreciated...
No, but you can use a TIMESTAMP field to store when the row was inserted / modified and occasionally delete rows that are older than x minutes.
DELETE FROM your_table
WHERE your_timestamp < NOW() - interval 5 minute
To solve your actual problem though, I'd suggest having a table with a row for each user and the last time they sent a message. Assuming it is indexed correctly and your queries are efficient you probably won't ever need to delete any rows from this table, except perhaps if you use a foreign key to the user table and delete the corresponding user. When a user sends a message insert a row if it already exists, otherwise update the existing row (you can use for example the MySQL extension REPLACE for this if you wish).
I would recommend that you add a WHERE clause concerning time to the SELECT "simply check if the IP is in the table"
SELECT * FROM table WHERE ip = <whatever> and timestamp > NOW() - 3*60
Then maybe empty out that table once every night.
I'd make a column that has the timestamp of the last sent message and another that has the total number of posts. Before updating the table check if at least X minutes has passed since the last post. If so, change the total number of posts to 1, otherwise increment the value by 1.
One approach that doesn't involve deleting the IP addresses after a certain interval is to store the addresses as "temporal" data, i.e. records that are only valid for a certain period.
Simplest way to do that would be to add a timestamp column to the table and, when entering an IP, capture either the time it was entered into the table, or the time after which it is no longer being "limited".
The code that grabs IPs to be limited then checks the timestamp to see if it's either:
older than a certain threshold (e.g. if you recorded the IP more than an hour ago, ignore it) or
the current time is greater than the expiry date stored there (e.g. if an IP's timestamp says 2010-11-23 23:59:59 and that is in the past, ignore it)
depending on what you choose the timestamp to represent.
The other solutions here using a timestamp and a cron job are probably your best option, but if you insist on mysql handling this itself, you could use Events. They're like cron jobs, except mysql handles the scheduling itself. It requires 5.1+ though.