【发布时间】:2018-03-03 13:44:50
【问题描述】:
我有一个名为 Posts 的 mysql 表,其中包含一个名为 post_date 的日期时间字段
下面是数据库表的截图:
我想将第一行的 post_date 设置为今天的日期,然后在之后的每个 post_dates 中添加一天,直到它们全部更新 - 所以如果今天是 2017 年 9 月 22 日并且有 5 行,post_date 字段将是:
2017-09-22 12:00:00
2017-09-23 12:00:00
2017-09-24 12:00:00
2017-09-25 12:00:00
2017-09-26 12:00:00
如果有 50 行,它会提前 50 天,等等。
我的最新方法是使用 mysqli_num_rows() 获取总行数,然后将该值存储在一个变量中。
然后我尝试使用date() 和mktime() 创建“开始日期”和“结束日期”,然后使用 foreach 循环更新此范围内的日期。
但这不起作用。代码如下:
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//begin if statement to get row count
if ($result = mysqli_query($conn, "SELECT * FROM Posts")) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
/* close result set */
mysqli_free_result($result);
}
//end if statement to get row count
// create foreach loop with a date range equal to the number of rows, and update the post_date values by one day as many times as there are rows in the table
$today = date("Y-m-d");
$begin = new DateTime($today);
list($y,$m,$d)=explode('-',$today);
$day_last = Date("Y-m-d", mktime(0,0,0,$m,$d+$row_cnt,$y));
$end = new DateTime($day_last);
$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);
foreach($daterange as $date) {
$sql_date_update = "UPDATE Posts SET post_date = $date->format("Y-m-d h:i:s")";
if ($conn->query($sql_date_update) === TRUE) {
echo "Record updated successfully"."<br>";
} else {
echo "Error updating record: " . $conn->error;
}
}
我尝试了很多不同的方法,但没有任何效果。任何提示将不胜感激。
【问题讨论】:
标签: php mysql date datetime increment