How to INSERT days to keep a MYSQL calendar table current? - php

I have a calendar table in my MYSQL database with one field named datefield (type DATE).
Previously I inserted dates from 2008-01-01 to 2010-01-01 but now I want to add every day until the current date. Unfortunately, I'm completely forgotten how I did this.
I'm also wondering if there is any way to automate the process of keeping this table current.
I'm using PHP so I guess I could do a new INSERT every day? Or is there some way to do this directly in MYSQL?
thanks,
tim

Here's a quick hack:
drop table if exists dates;
create table dates(datefield date);
drop procedure if exists insertDates;
delimiter $$
create procedure insertDates(start_date date)
begin
set #days = 0;
set #end_date = str_to_date('1970-01-01', '%Y-%m-%d');
while (#end_date < curdate()) do
insert into dates
select
date_add(start_date, interval #days day)
from (select #days:=#days+1) r
;
set #end_date:=(select max(datefield) from dates);
end while
;
end $$
delimiter ;
call insertDates('2012-06-06');
select * from dates;
For the daily insert you can try a cron job or MySQL offers "EVENTS", something like:
CREATE EVENT yourDB_Schema.insertDateEachDay
ON SCHEDULE EVERY 1 DAY
DO
INSERT INTO yourTable (yourDateColumn) VALUES (CURDATE());
Read more about it here:
MySQL Create Event manual entry
An event is associated with a schema. If no schema is indicated as
part of event_name, the default (current) schema is assumed.
_
Not specifying STARTS is the same as using STARTS
CURRENT_TIMESTAMP—that is, the action specified for the event begins
repeating immediately upon creation of the event.

I think the easiest way to do what you describe is set up a daily recurring task to run a php script, such as a cron job. There is also a web based provider that will call a script from your webserver on a cheap, recurring schedule. http://webcron.org

Related

Database which can remove records automatically by checking date column

Suppose there is a database which contains a table that has date and events column, there are total 10 records now I want that the records which are older then the current date should automatically be deleted and the present date records should be present in the database so as the future records should also be present, does anyone know something like this or can help me how to achieve this. any references would be helpful. I am open to php, phpmyadmin, sql. Any help would be appreciated.
First it's too broad. You can consider using MySQL Event Scheduler for this purpose. Which you can set to run on every 24 hours and delete all records less than NOW()
Activate event support :
SET GLOBAL event_scheduler = ON;
Add sheduler :
DELIMITER |
DROP EVENT IF EXISTS `clear_old_rows`|
CREATE EVENT `clear_old_rows`
ON SCHEDULE
EVERY 1 HOUR STARTS CURRENT_TIMESTAMP
ON COMPLETION PRESERVE
ENABLE
COMMENT 'clear all rows < CURRENT_TIMESTAMP'
DO
BEGIN
DELETE FROM tablename WHERE date < CURRENT_TIMESTAMP ;
END |
DELIMITER ;

How to increment mysql data after a fixed time slot automatically?

For example, I am creating a student management system and I want to increase the student standard after every year. If student is admitted in 1st standard then next year he would be in 2nd after that 3rd and so on.. Please help!
you can use MySQL EVENT like
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 YEAR
DO
UPDATE `student` SET `standard` = `standard` + 1
WHERE some_ID_Column = value;
Set up a cron job that runs nightly and run a stored procedure that checks if the students have reached the condition for the next standard and if they have update the records.

MySQL - How to decrement int value every 24 hours?

I am working a system in PHP. In my MySQL have a table borrow. Inside borrow is borrow_status a varchar and borrow_remain which is an int value. When the user click the submit button. The query will run something like
INSERT INTO `borrow`( `borrow_status`,`borrow_remain`) VALUES ('Borrowing',3)
How can I decrement the borrow_remain value per 24 hours then UPDATE the borrow_status to Finish when it reaches zero?
EDIT: I also have a book table, that have a book_quantity, my only concern is that the book_quantity must increment if the borrow_status is updated to Finish.
You can implement the above scenario following the three steps given below :
1) First you have to enable Mysql event scheduler.
SET GLOBAL event_scheduler = 1;
2) Create a procedure in mysql that will do the borrow status update related functionalities.
delimiter //
CREATE PROCEDURE UBS()
BEGIN
UPDATE borrow set borrow_remain = borrow_remain - 1
WHERE borrow_status='borrowing';
UPDATE borrow SET borrow_status = 'finished'
WHERE borrow_remain=0;
END //
delimiter ;
3) Create an event which will be scheduled in 24 hours interval.
CREATE
EVENT UBSEvent
ON SCHEDULE EVERY 24 HOUR STARTS '2015-03-04 00:00:00'
ON COMPLETION PRESERVE
ENABLE
DO
CALL UBS();
Note :
UBS is the procedure name.[ UBS = Update Borrow Status (just a
relevant abbreviation ]
The event will start from tomorrow (4 March 2015) at 12:00 AM
Have a nice day!
EDIT: To increment book_count in book table whenever a borrow_status in borrow table gets updated to 'finished' you need a trigger.
Suppose you have a book table where the count of the book is denoted by book_count; Then the following trigger will do what you want.
DELIMITER $$
CREATE TRIGGER IncBookCount AFTER UPDATE ON borrow
FOR EACH ROW
BEGIN
IF NEW.borrow_status = 'finished' THEN
UPDATE book SET book_count = book_count+1;
END IF;
END $$
DELIMITER;
SUGGESTION : You need to improve your database design. Otherwise you might get more troubles in designing a complex architecture in future. Stay well!
Have you look at Events in mySQL? You can create an event and set it to run on a particular schedule. That might be the ticket for your problem!
You need to have mysql version 5.5 to use event. May be your desired event looks like this:
CREATE EVENT update_borrow
ON SCHEDULE EVERY 24 HOUR
STARTS CURRENT_TIMESTAMP
DO
BEGIN
UPDATE borrow SET borrow_remain = borrow_remain - 1 WHERE borrow_remain > 0;
UPDATE borrow SET borrow_status = 'FINISH' WHERE borrow_remain = 0;
END
You could also set a cronjob that executes a piece of code to decrement "borrow_remain" and updates "borrow_status" accordingly. If your hosting has cPanel it's pretty easy: https://documentation.cpanel.net/display/ALD/Cron+Jobs

Insert data on 1st day of every month only once

I want to insert data into a table on 1st day of every month. And it has to be just for one time. I mean one row for each 1st day of month. I am doing all this in a PHP file and using mySql.
So far i got this much-
if(Date('j')==1)
{
$query = select 1 from table where extract (year from t1) = extract(year from now()) and extract(month from t1) = extract(month from now()) LIMIT 1
if (#mysql_num_rows(mysql_query($query)) == 0)
{
//perform insert operation
}
}
I haven't tried this query till yet.
Maybe this will do the trick
SELECT * FROM xxx WHERE (DATE_FORMAT(CURDATE() ,'%d')==1)
SELECT DATEADD(mm, DATEDIFF(mm,0,GETDATE())-1,0) as StartOfLastMonth
SELECT DATEADD(mm, DATEDIFF(mm,0,GETDATE()),0) as StartOfThisMonth
SELECT DATEADD(mm, DATEDIFF(mm,0,GETDATE()),0) as StartOfNextMonth
Try out below event scheduler
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 MONTH
DO
"YOUR QUERY"
Your have to run this on the date on which you want to run on 1 month interval.
You get more information on http://dev.mysql.com/doc/refman/5.1/ja/create-event.html
You have two solutions, depending on what you exactly want.
If your data must be inserted at the first day: the only way is to insert it using a cron job which run at the correct time. You can use the mysql scheduler to do the job if it's only mysql related.
If your data need to be in the table after the first day, but you don't care if it is added in realtime or only when you access that data then you don't need a cron job. You can check for that data when you access it, then insert it before reading if it's not already present.
you can achieve with mysql event scheduler--
http://dev.mysql.com/doc/refman/5.1/en/events.html
CREATE EVENT IF NOT EXISTS `my_old_data_cleaner_event`
ON SCHEDULE EVERY 23 DAY_HOUR
COMMENT 'Clean up Service Start at 11:00PM daily!'
DO DELETE FROM my_table WHERE created_date < (NOW() - INTERVAL 1 MONTH);
OR for Stored Procedure.
CREATE EVENT IF NOT EXISTS `my_old_data_cleaner_event`
ON SCHEDULE EVERY 23 DAY_HOUR
DO CALL my_sp_cleanup_old_data();

Remove Mysql row after specified time

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

Categories