MySQL event scheduler refresh error PHP - php

I have this code in my php, but everytime I refresh the page it says Event 'expired' already exist. any way that it would not pop up anymore?
$auto = mysql_query("CREATE EVENT expired ON SCHEDULE EVERY 1 MINUTE DO UPDATE stocks SET status='expired' WHERE expdate < NOW() ") or die (mysql_error());
Thanks

By the looks of it, every time you refresh the page it will attempt to create a new event with the name expired.
If you only want to create one event and never worry about it again (and based on that query, it looks like you do), you should just do it once in the database directly.
However, if you really want to keep it in your code, you could use IF NOT EXISTS: https://dev.mysql.com/doc/refman/5.1/en/create-event.html
CREATE EVENT IF NOT EXISTS expired ON SCHEDULE EVERY 1 MINUTE DO UPDATE stocks SET status='expired' WHERE expdate < NOW()
However, if all you want to do is determine the state of a stock at a give time, it might make more sense to use MySQL's IF logic to derive a status at any point (and not actually have a status field in your table): https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if
SELECT *, IF(expdate < NOW(), "expired", IF(expdate < NOW() + INTERVAL 10 DAYS), "critical", "fine")) AS status FROM stocks

Related

how to make data base to delete info after some time using php?

I need to delete particular info from data base using only php, after some time without using cron system. How can I realize it?
Without cron there is only one way i.e hook that deletion code with some event e.g login of any user. As a new user logs in you can run that code
Include a timestamp in the database table. Then have a function in your PHP that deletes all records that are more than X minutes old whenever the PHP is run.
You can use a query such as this (for all records more than a day old).
DELETE FROM `table`
WHERE `timestamp` < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))

Daily cron to poll mysql and update status based on timestamp

I have a db full of email users that lists the date and time they signed up in a column called signup_date using the DATETIME type (it uses now() ) and I also have an expire_date column which lists the same format but exactly a year later using ADDDATE(NOW(), INTERVAL 365 DAY)
I have added a status column with values being either 0 or 1. I guess this can be an ENUM type. Upon registration, status is set to 1 for active.
What I want is that if the timestamp of the expire_date is older than the current time, the cron should execute an update on that row of the user setting the status to 0. In postfix, I altered the query and appended the status=1 so that it will select the user with only status of 1. If the status isn't 1, then the user will not be found and won't be able to log in. This cron can run daily. I'm not too anal about having it run every second. Users can renew their emails within the next day. So this is my simple way of expiring emails, if they are not active or so after a year. What I need help with is constructing the cron. Should this be done with just php or does some bash need to be used? Im unclear of how to structure the script. Thanks.
Why maintain an additional flag column? You can calculate the status on the fly
SELECT *
FROM table_name
WHERE expire_date > NOW()
This will return only unexpired rows
If you need status to be produced as a column you can do
SELECT *, (expire_date > NOW()) status
FROM table_name

Change record automatically

On the website i'm developing i'm making a system for ban and unban users.
In my database i have a table 'banned' with fields about the bans (userID, active, date was made, reason ecc).
What i want to do is:
Add another field for expire date, and when this date occur, change automatically the field 'active' to 0.
How i can do that?
I would not use two fields like you did -- because I would not want to depend on a task to change back the active field when the un-ban date is reached.
Instead, I would only use one datetime field, called like banned_until; and this field would either:
Be NULL when the user is not banned,
Or contain the date until which the user is banned.
Then, when the user tries to do something (log-in, post, ...), I would check that :
This field is NULL, in which case the user is not banned
Or that the date contained in this field is in the past, in which can the user has been banned, but is no longer.
In the second case, you could even reset the field to NULL, as the un-ban date has been reached.
Its either you use a cron script or when getting banned users, you apply a where clause to check if the the ban has expired
Create a php script that will check if time is passed the expiration date. SQL will be something like this:
UPDATE banned SET active=0 WHERE expire_date<=NOW()
Save it as a for example task.php
Then create a cron task with crontab -e
*/10 * * * * php /path/to/your/taks/task.php
And this will cause this script to be executed every 10min and unban all banned ppl.
--
There are other ways, perhaps better ones, like e.g. Pascal described, but this answer is for your idea.
You can compare expiry_date value with current_date to check if a user is active or not on his login.
SELECT
( DATE_FORMAT( expiry_date_field, '%Y-%m-%d' )
<
DATE_FORMAT( CURRENT_DATE, '%Y-%m-%d' )
) AS isActive
FROM
banned
WHERE
user_id=?;
A 0 returned represents in-active status and 1 as active.
But irrespective of a user's login, if you want to maintain active status of users, you can achieve this using the Event Scheduler.
Following example gives you an idea in implementing one.
drop event if exists event_user_bans_scheduling;
delimiter //
create event if not exists event_user_bans_scheduling
-- on schedule every 86400 second starts 00:00:00
-- at timestamp( adddate( current_date, 1 ),'00:00:00' )
on schedule every 1 day starts timestamp( current_date + 1, '00:00:01' )
comment 'Scheduler to update active status of users'
do
UPDATE my_app_db.banned
SET ACTIVE=0
WHERE
date_format( expiry_date_field,'%Y-%m-%d' ) = date_format( CURRENT_DATE, '%Y-%m-%d' );
;
//
delimiter ;
Note:
The global event_scheduler system variable determines whether the Event Scheduler is enabled and running on the server. Read complete notes on Event Scheduler Configuration before working on MySQL events.

How to auto update a record in database?

I have a jobs table in which I inserts new jobs.
This table also contains the job post date.
By default the job status is open when a new insertion take place.
Now I want to change the status of the job from open to close when the jobs becomes older than 30 days.
How will I do this?
Try creating a event which runs every day like below
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO
UPDATE my_table SET status ='closed'
WHERE post_date > DATE_ADD(now(), INTERVAL -30 DAY)
AND status='open'
-- Update Changed syntax
CREATE EVENT myevent
ON SCHEDULE EVERY 24 HOUR
DO
UPDATE my_table SET status ='closed'
WHERE post_date > DATE_ADD(now(), INTERVAL -30 DAY)
AND status='open'
Use a cron job to handle this. http://en.wikipedia.org/wiki/Cron
If you can't handle crons, you could do a "poor man's cron". Means the actual process that updates all of your jobs records takes place when someone visits your page (with additional checks when the last run was). If you're doing it the "poor" way I suggest to fire off another thread to keep your site responsible.

Making an auction script start and stop auctions at specific times.

I am building a simple auction application. I need auctions to start and end at certain times. Should the page that displays the open auctions just run a query to find all auctions where current time is after the start time and before the end time? Or would it bet better to have a script that sets a "active" column to True? If this is the case would I have to have some type of cronjob setup?
No cron and no "active" column is required. Just list auctions using something like:
select *
from auctions
where
start < now()
and end > now()
When user is placing a bid use the following:
update auctions set
bid = $bid,
highest_bidder = $bidding_user_id
where
id = $this_auction_id
and start < now()
and end > now()
and bid < $bid
Then check if query has affected a row. If yes - bid is successful, current user is highest bidder. If no - bid is too low or auction has finished. You can figure out that later by fetching auction row again and checking bidder id.
Just set a "close_time" field in the mysql table with your auction. When you add the row, populate that field with a time() + whatever to set the close_time to represent some point in the future.
Then setup a script which runs a simple query:
'UPDATE auctions_table SET active = FALSE WHERE active = TRUE AND close_time <= UNIX_TIMESTAMP()'
Save that query to a php page called something like close_active_auctions.php and set that up on a cron for once every 10 seconds or so (or however often you need).

Categories