我试图在数据库中插入日期数组,但程序没有表现。我做错了什么。
此插入 NULL :
// initialize the array with first date
$dates = array(strtotime("+17 days", strtotime($period_startdate)));
// now loop 26 times to get the next 26 dates
for ($i = 1; $i <= 26; $i++) {
// add 14 days to previous date in the array
$dates[] = strtotime("+14 days", $dates[$i-1]);
}
// echo the results
foreach ($dates as $date) {
// prepare and bind for paydates
$insertpaydates= $db->prepare("INSERT INTO paydates (payroll_secret_id,paydate) VALUES (?,?)");
$insertpaydates->bind_param("ss",$secret_id,$dates[$date]);
}
此插入只有一行和错误的日期(1970-01-01)
// initialize the array with first date
$dates = array(strtotime("+17 days", strtotime($period_startdate)));
// now loop 26 times to get the next 26 dates
for ($i = 1; $i <= 26; $i++) {
// add 14 days to previous date in the array
$dates[] = strtotime("+14 days", $dates[$i-1]);
}
// echo the results
foreach ($dates as $date) {
$Item_Date[$date] = date("Y-m-d", strtotime($Item_Date[$date]));
// prepare and bind for paydates
$insertpaydates= $db->prepare("INSERT INTO paydates (payroll_secret_id,paydate) VALUES (?,?)");
$insertpaydates->bind_param("ss",$secret_id,$Item_Date[$date] );
}
答案 0 :(得分:1)
第一个代码片段的问题在foreach循环中。循环遍历数组时,第二个参数将是数组的实际条目,而不仅仅是键。因此,不要使用$dates[$date]
,而应在循环中使用$date
。
每次将新参数绑定到语句时,您还必须执行查询,否则您只需覆盖旧参数并在循环后执行单个执行。因此,您应该将执行添加到foreach
- 循环,以便它在每次迭代时写入。
要提高代码性能,您应该做的第三件事是将SQL Prepare语句移到循环外部。而不是准备语句26次,你只能做一次,然后用不同的值执行26次。这将在执行时间上产生很大的不同。
在本文的下面评论中,您似乎在MySQL数据库中使用了错误的数据和数据类型组合。您正在尝试将整数时间戳写入DateTime字段。在编写之前,您应该将其转换为有效的日期格式。
所以最终的代码是:
// Convert our $_POST value to a timestamp.
$period_startdate = strtotime($period_startdate);
// We init the first date value.
$dates = array(
date('Y-m-d H:i:s', strtotime("+17 days", $period_startdate)),
);
for ($i = 1; $i <= 26; $i++) {
// Add 14 days to previous date in the array.
// Notice we have to convert the previous date in the array to a timestamp using strtotime().
$dates[] = date('Y-m-d H:i:s', strtotime("+14 days", strtotime($dates[$i-1])));
}
// We prepare our statement before the loop to avoid preparing it
// multiple times. This saves performance.
$insertpaydates = $db->prepare("INSERT INTO paydates (payroll_secret_id,paydate) VALUES (?,?)");
foreach ($dates as $date) {
// Here we change from $dates[$date] to simply $date
$insertpaydates->bind_param("ss", $secret_id, $date);
// Here we execute the query for each date.
$insertpaydates->execute();
}