使用php pdo为年中的每个日期添加一行

时间:2014-06-16 11:17:56

标签: php mysql sql

我需要为我的数据添加365/366行,以便在某年内为每个日期添加(等2014年)......

我有:

//something like for each date in this year add row with data...
     $STH1 = $db->prepare("INSERT INTO workhours (ID_radnika,ime,datum,user_id) values ($orderID,:1,HOW TO FOREACH DATE,:2)");  
          $STH1->bindParam(':1', $_POST['ime']);
          $STH1->bindParam(':2', $user_id);

          $STH1->execute();

所以这是一个简单的问题。现在我需要我知道的数据(ID_radnika,ime,user_id)添加365行但仅更改数据(日期)

最好的方法是什么?

3 个答案:

答案 0 :(得分:1)

试试这个

CREATE PROCEDURE `sp_test`(IN id INT, In ime VARchar(20),In userid INT)
BEGIN
DECLARE start_date DATE default '2020-06-16';
DECLARE end_date DATE default '2021-06-16';
DECLARE DiffDate int default 1;
SELECT DATEDIFF(end_date,start_date) AS DiffDate
into DiffDate;
while DiffDate>0 do
  INSERT INTO workhours(ID_radnika,ime,datum,user_id)
  values (id,ime,start_date,userid);
    select  DATE_ADD(start_date, INTERVAL 1 DAY)
    into start_date;
    SELECT DATEDIFF(end_date,start_date) AS DiffDate
    into DiffDate;
end while;
END

答案 1 :(得分:0)

添加另一个参数:

$STH1 = $db->prepare("INSERT INTO workhours (ID_radnika,ime,datum,user_id) values ($orderID,:ime,:date,:uid)");

执行更改的参数:

    $max_days = ((((($year%4)==0)&&((($year%100)!=0)||(($year%400)==0))))?366:365);
    $startOfYear = strtotime(date('Y-01-01 0:00:00'));
    for ($i = 0; $i < $max_days; $i++) {
        $STH1->execute(array(
            ':ime' => $_POST['ime'],
            ':uid' => $user_id,
            ':date' => $startOfYear + $i*86400,
   ));

如果您愿意,可以使用单个查询执行此操作。然后你需要做:

$values      = array();
$startOfYear = strtotime(date('Y-01-01 0:00:00'));
$max_days = ((((($year%4)==0)&&((($year%100)!=0)||(($year%400)==0))))?366:365);
for ($i = 0; $i < $max_days; $i++) {
    $values[] = "($orderID, :ime, ".($startOfYear + $i * 86400).", :uid)";
}
$stm = $db->prepare("INSERT INTO workhours (ID_radnika,ime,datum,user_id) values ".implode(',', $values));
$stm->execute(array(':ime' => $_POST['ime'], ':uid' => $user_id));

答案 2 :(得分:0)

您可以在MySQL中使用WHILE,如下所述:http://dev.mysql.com/doc/refman/5.7/en/while.html

DECLARE v INT DEFAULT 365;
WHILE v > 0 DO
    ... insert to ...
    SET v = v - 1;
END WHILE;

您还可以在手册中找到所需的日期操作功能:http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html

您需要的是:MAKEDATE(year, dayofyear)