MySQL - automatically update row after x seconds of inactivity (set expiration time) - php

For an art project I am trying to set up an order site.
The concept allows users to book a max. of two time slots with each artist. There are 12 slots per artist, but each slot with a specific definition (so each is unique). The slots are only available for a very limited time and hopefully booked fast. So there will be a lot of requests in a short period of time. I have to make sure each article/slot is only offered to a single user at a time and cannot be double booked.
My idea was, to check for the next unbooked slot(s) (status="free) and on that request update the status of the corresponding row in the table to status="locked". If the user proceeds to actually book the slot, the status is updated to "booked".
If a user clicks "cancel" I can release the article by updating the row to status="free".
However, it is not unlikely that users just abandon the site and I don't see a way to check for that. The slot would remain "locked". I was thinking, there might be a way to automatically reset the status e.g. 120 seconds after is was "locked" and show a countdown to the users. This could even enhance the excitement factor.
I don't think a cron job would work as I need the anchor to be the last update of the row and not a specific datetime.
I looked into MySQL events but understood that I cannot manipulate the data of the table it is attached to.
I would greatly appreciate any ideas.
Thanks,
Sam

In your db your status table add a datetime field.
When someone lock a slot you also save the current time using NOW()
When someone consult the slots you perform and update and free the inactive slots
Update slots
SET locked = false
WHERE `datetime`> NOW() - INTERVAL 15 MINUTE;
SELECT *
FROM slots
WHERE locked = false;

Related

Building a scheduler with sql, php. Most efficient way

I am creating a system that requires a schedular for a particular task. Users may pick from times 24 hours a day, 7 days a week.
I came up with a few options for the database storage, but I don't think either one is the most efficient design, so I'm hoping for some possible alternatives that may be more efficient.
On the user side I created a grid of buttons with 2 loops to create the days, and the times, and I set each a unique value of $timeValue = "d".$j."-t".$i;
So d1-t0 will be Saturday at Midnight d3-t12= Tuesday at Noon, and so forth.
So, in the database I was first going to simply have a ID, day, time set up, but that would result in a possible 168 rows per event
Then I tried an ID, day, and time 0-23 (a column for each hour of the day) And I was simply going to have a boolean set up. 0 if not selected, 1 if it is.
This would result in 7 rows per event, but I think querying that data might be a pain.
I need to perform a few functions on this data. On each day, list the number of selected times into an array. But I don't believe having a select statement of SELECT * from schedule where time0, =1 or time1= 1 .... ect will work, nor will it produce the desired array. (times=(0,3,5,6,7...)
So, this isnt going to work well.
My overall system will need to also know every event that has each time selected for a mass posting.
"Select * from table where time = $time (0-23) and day= $day (1-7)
Do action with data...
So with this requirement, I'm going to assume that storing the times as an array within the database is likely not the most efficient way either.
So am I stuck with needing up to 168 rows of data per event, or is there a better way I am missing? Thanks
Update:
To give a little more clarity on what I need to accomplish:
Users will be creating event campaigns in which other users can bid on various time slots for something to happen. There will likely be 10-100 thousand of these campaigns at any one time and they are ongoing until the creator stops them. The campaign creators can define the time slots available for their campaign.
At the designated time each day the system will find every campaign that has an event scheduled and perform the event.
So the first requirement is to know which time slots are available for the campaign, and then I need the system to quickly identify campaigns that have an event on each hour and day and perform it automatically.

PHP/MySQL update mysql field after 10 minutes has elapsed.

As the title reads, I am looking for a way to update a mysql field after 10 minutes has elapsed of a query being run.
Something like below is an example without the time restraint:
mysql_query("UPDATE `players` SET `playcoins`=TRUNCATE(ROUND((`playcoins`+$amount),9),8) WHERE `id`=$player[id] LIMIT 1");
Any ideas?
MySQL databases have a class of object called an EVENT. It's basically a hunk of SQL code that runs at particular time, or on a particular interval.
You could use code like this to create an event to do what you require at the right time in history. This particular code will create an event that runs just once, ten minutes in the future.
DELIMITER $$
DROP EVENT IF EXISTS coins_user12345$$
CREATE EVENT coins_user12345
ON SCHEDULE
AT NOW() + INTERVAL 10 MINUTE
ON COMPLETION NOT PRESERVE
ENABLE
DO BEGIN
UPDATE players
SET playcoins=TRUNCATE(ROUND((playcoins+123),9),8)
WHERE id=12345
LIMIT 1;
END$$
DELIMITER ;
To use these EVENT objects, you have to configure the event scheduler correctly. Read this. http://dev.mysql.com/doc/refman/5.6/en/events-configuration.html Some cheap shared hosting providers don't allow the use of events, so this is not guaranteed to work.
You go it the wrong way. Sure you can do it. And you can do it with PHP. But you shouldn't. PHP is not the right language to do such a task. Before I starting talk about shell_execute and sleep, which would be the core elements, you need to do this, I offer you another solution.
If I see right, you want to give a player every 10 minutes, some coins.
The right approach would´basicly be:
Save the last time the player has get coins in the database. If you get the player coins, you first want to check, the last time you give the player coins. Now calculate, how much he has earned in this time difference. Finaly add this to his balance and update the field, where you save the last time, the player has earned coins.
An alternative would be a Cronjob/Scheduled Task to a PHP file, which is called every 10 minutes, to give each player the coins, he should get.

Programming logic - update the database only one time after specific time interval

I am developing ecommerce store in php and I have some problem in creating a logic. The problem is I have a store page where I am showing some products. all the products have some time interval,after interval passes the products will no longer be display there.
For example
Product: jeans
time left: 10 days.
after 10 days jeans product will no longer be there. in database I have a set a field with the name active_status which accepts Y or N..
I know that I can simply run the update query and set the status to "N" after time passes. here in this example after 10 days
BUT the question is WHEN DO I RUN THIS UPDATE QUERY ?
should I always check time and run again and again update query and set STATUS TO 'N'??? IS that is the only solution ?
I mean usually we do like for example if customer logins we set some status or any other event but here we are setting the status against checking the time. Hopefully you have understand my question
In the db I am saving the start time and number of days which user puts through the admin panel
My first shot would be cron, php script and properties table (if needed, because for simple uses you could just store expiration date inside business entity).
Cron runs php script periodically (e.g. once a day),
scripts checks if there is anything to delete, based on properties table, or entity properties.
If there is anything to delete, script performs deletion of selected content.
That's all and it is in fact very popular scenario.
More on cron: http://www.pantz.org/software/cron/croninfo.html
Here is my logic i hope it will helps i think
While Publishing the product we have to maintain the time interval of that product for example if you want to display the product for 10 days give 10 days and date of publish product.
By comparing with that date and number of days given for time interval with the present date i.e today's date
Can you check with this

MySQL Table Setup for today, yesterday, monthly logs

I am working on a PHP / MySQL stat logging program and am trying to find the best MySQL DB Structure for it.
There is a part where visitors will be able to see up to the date stats (i.e the latest 20 entries) but also will be able to see today's overall, yesterday's overall, last 7 days overall and last 30 days overall stats.
From the data I'm pulling the real-time stats will be updated every 60 seconds with at least 10 new entries per update.
Is my logic correct to setup two tables ... one to act as "today's" stats and another to act as the overall archive ... like:
todays_stats
id
from_url
entry_date
overall_stats
id
from_url
entry_date
Then double insert for each new entry but truncate the todays_stats at midnight every night via a cron job?
Or is there a more efficient way of doing this?
It depends on your daily stat row count, whether to delete historical data, and how much indexes you has. We need to delete historical data and has 7~8 indexes with large amount of stat data, so we separate data into daily tables and write stored procedures to fetch data(last day, last 7 day, last 30 day etc). Dropping table is much more faster than DELETE FROM table WHERE index=6-month-old-data
I think best way is to be keep one table that will hold the current data set, then you will have separate table for overall stats and at midnight you will insert all data from current to overall table with
INSERT INTO `overall` SELECT * FROM `current`
query. Then you will truncate the current table after successful data copying.

Online or offline function PHP

I'm working on a "community". And of course I would like to be able to tell if a user is online or offline.
I've created so that when you log in a row in my table UPDATE's to 1 (default is 0) and then they're online. And when they log out they're offline. But if they don't press the Log out button, they will be online until they press that button.
So what I would like to create is:
After 5 minutes of inactivity the row in my database should UPDATE to 0.
What I'm looking for is how to do this the easiest way. Should I make an mysql_query which UPDATE's the row to 1 every time a page is loaded. Or is there another way to do it?
Instead of using a boolean "Online" field, use a DateTime. When a user makes a request to the page, update the DateTime to NOW(). When you are gathering your list of current users online, your WHERE clause would be something like WHERE lastSeen > DATE_SUB(NOW(), INTERVAL 5 Minutes)
Update: To retrieve individual online status.
select if(lastSeen > date_sub(now(), interval 15 minutes), 1, 0) as status from table where userid=$userid
This tutorial is quite handy: Who Is Online Widget With PHP, MySQL & jQuery
Well, if you don't want to set up a cron job, that would execute some code every 5 minutes, you have no options. But, actually, I think the following approach would be much more efficient:
Change your 1/0 column to timestamp
On each user request update that timestamp to current DateTime.
When checking for active users, check if that timestamp is less than 5 minutes from now
This way you'll be having actual data on users and no recurring queries - just one additional update per request
If you will update the row only on page load, then some of information would be incorrect.
Let's assume that user have opened page and is writing really long text or something. He is doing it for half an hour now. And your database ny now is already updated and he is counted as offline user.
I would write javascript that pings you back each 5 minutes, if opened tab is active.
This ping updates database field 'last_activity' to NOW(). And to count online users, or check if user is online you'll need to compare 'last_activity' to NOW() minus five minutes.
Simpliest ways (IMHO):
You can count sessions in session_save_path() dir.
you can store last visit timestamp in DB, and count rows with (timestamp > current_timestamp - somedelay).

Categories