gpt4 book ai didi

php 更新 mysql 表每一列中的日期,以便它们自动增加一天

转载 作者:行者123 更新时间:2023-11-29 02:13:08 26 4
gpt4 key购买 nike

我有一个名为 Posts 的 mysql 表,其中包含一个名为 post_date 的日期时间字段

这是数据库表的屏幕截图:

enter image description here

我想将第一行的 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;
}
}

我尝试了很多不同的方法,但没有任何效果。任何提示将不胜感激。

最佳答案

您可以在此处尝试使用生成的列:

CREATE TABLE Posts (
id INT NOT NULL AUTO_INCREMENT,
post_date DATETIME AS DATE_ADD('2017-09-22', INTERVAL id DAY);
);

此方法需要 MySQL 5.7.6 或更高版本。它直接将常规自动增量列与日期计数器耦合。我认为只有将生成日期基于固定的初始日期才有意义。这与基于零的自动增量列的行为相匹配。

关于php 更新 mysql 表每一列中的日期,以便它们自动增加一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46356918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com