looping a SQL insert statement with updating dates
What do I need to do is run insert the same thing into a database only changing the date.
i.e
INSERT INTO bs_events
(
eventDate,
eventTime,
title,
spaces,
description,
entryFee,
payment_required,
max_qty,
allow_multiple
)
VALUES (
'2011-03-02 00:00:00',
'10:00',
'Carpet Cleaner 3000',
'4',
'This is rad',
'25.99',
'1',
'1',
'2'
)
开发者_开发问答So I need to run this loop for a year or month or 2 years and have it add to the database but the date needs to change each day
I've got no idea how I go about making a script to do this so any help would be appreciated
Thanks
Here's an example. It does it all in one query.
$row = array(
'2011-03-02 00:00:00',
'10:00',
'Carpet Cleaner 3000',
'4',
'This is rad',
'25.99',
'1',
'1',
'2'
);
$rows = array();
$end = new DateTime('2012-01-01');
for($date = new DateTime($row[0]); $date < $end; $date->modify('+1 day')) {
$row[0] = $date->format('Y-m-d H:i:s');
$rows[] = sprintf("('%s')", implode("','", $row));
}
$query = 'INSERT INTO bs_events
(
eventDate,
eventTime,
title,
spaces,
description,
entryFee,
payment_required,
max_qty,
allow_multiple
) VALUES '.implode(',', $rows);
Note: This works because the row data is known... if you accepting user input, make sure you are checking for SQL injection.
Instead of inserting the date directly maybe you could use now()
, assuming that it is the current date you want to insert.
The following will insert the current date instead of a preset date. This assumes you're using MySQL.
INSERT INTO bs_events
(
eventDate,
eventTime,
title,
spaces,
description,
entryFee,
payment_required,
max_qty,
allow_multiple
)
VALUES (
DATE_FORMAT(CURDATE(),'%Y-%m-%d %H:%i:%s'),
'10:00',
'Carpet Cleaner 3000',
'4',
'This is rad',
'25.99',
'1',
'1',
'2'
);
You can create a stored procedure to loop and insert as many as you want starting from today using this:
DELIMITER //
CREATE PROCEDURE loopInsert()
BEGIN
DECLARE a INT DEFAULT 0;
myloop: LOOP
INSERT INTO bs_events
(
eventDate,
eventTime,
title,
spaces,
description,
entryFee,
payment_required,
max_qty,
allow_multiple
)
VALUES (
DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL a DAY),'%Y-%m-%d %H:%i:%s'),
'10:00',
'Carpet Cleaner 3000',
'4',
'This is rad',
'25.99',
'1',
'1',
'2'
);
SET a = a + 1;
IF a = 6 THEN
LEAVE myloop;
END IF;
END LOOP myloop;
END//
DELIMITER ;
Then you can:
CALL loopInsert();
And it will insert a
days starting from today. The example would insert 6 days.
精彩评论