我的网站上有两个日期选择,管理员可以选择"start date"
和"end date"
。从开始到结束的所有日期将被上传到数据库。例如:
Start Date: 2015-01-01
End Date: 2015-01-05
Upload to database:
2015-01-01
2015-01-02
2015-01-03
2015-01-04
2015-01-05
我已经有一个代码来执行此操作,尽管它只将一个日期上传到数据库,即开始日期。有什么想法,我将如何工作上传所选的开始和结束日期之间的所有日期?这是我目前的代码:
if(isset($_POST['add'])){
$servername = "localhost";
$username = "u779108225_admin";
$password = "password";
$dbname = "u779108225_main";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$date_from = $_POST['date_from'];
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp
// Specify the end date. This date can be any English textual format
$date_to = $_POST['date_to'];
$date_to = strtotime($date_to); // Convert date to a UNIX timestamp
// Loop from the start date to end date and output all dates inbetween
for ($i=$date_from; $i<=$date_to; $i+=86400) {
$date = date("Y-m-d", $i);
$sql = "INSERT INTO calendar (date)
VALUES
('$date')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
// Specify the start date. This date can be any English textual format
}
答案 0 :(得分:3)
在每次循环迭代中覆盖$sql
时,您只执行上一次查询。将执行语句移动到循环中:
for ($i=$date_from; $i<=$date_to; $i+=86400) {
$date = date("Y-m-d", $i);
$sql = "INSERT INTO calendar (date) VALUES ('$date')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
或进行一次查询并执行:
$sql = "INSERT INTO calendar (date) VALUES ";
$values = array();
for ($i=$date_from; $i<=$date_to; $i+=86400) {
$date = date("Y-m-d", $i);
$values[] = "('$date')";
}
$sql .= implode(',', $values);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
答案 1 :(得分:1)
我更喜欢在时间戳等上使用DateTime对象。
你的for循环是多次设置查询,但是你只执行了一次查询。
这是使用DateTime的固定版本。
if(isset($_POST['add'])){
$servername = "localhost";
$username = "u779108225_admin";
$password = "password";
$dbname = "u779108225_main";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$date_from = $_POST['date_from'];
$date_from = new DateTime($date_from);
$date_to = $_POST['date_to'];
$date_to = new DateTime($date_to);
$cur_date = $date_from;
while($cur_date < $date_to) {
$date = $cur_date->format('Y-m-d');
$sql = "
INSERT INTO calendar (date)
VALUES
('$date');
";
$cur_date->modify('+1 day');
if ($conn->query($sql) === TRUE) {
echo "Date inserted: {$date}";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
}