我喜欢插入我的数据,如下面的结构。
+------+----+
|id|JAN||FEB|
+------+----+
|1 | 1|| 5|
+------+----+
|2 | 8|| 12|
+------+----+
|3 | 15|| 19|
+------+----+
|4 | 22|| 26|
+------+----+
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "epi";
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn)
{
die('Could not connect: ' . mysql_error());
}
$number_of_dates = 4;
$startDate_Jan = strtotime("2018-01-01");
for ($i = 0; $i <= $number_of_dates; $i++)
{
$date = strtotime("Monday +" . ($i * 1) . ' weeks', $startDate_Jan);
$month=date('m', $date).PHP_EOL;
$datex=date('d', $date).PHP_EOL;
$intmonth = intval($month);
$intdate = intval($datex);
echo $intdate;
echo "<br>";
$sql="INSERT INTO testdata (ID_DATE, EPI_DATE_JAN) VALUES ('','$intdate')";
$result = mysqli_query($conn, $sql);
}
$number_of_dates = 4;
$startDate_Feb = strtotime("2018-02-01");
for ($i = 0; $i <= $number_of_dates; $i++)
{
$date = strtotime("Monday +" . ($i * 1) . ' weeks', $startDate_Feb);
$month=date('m', $date).PHP_EOL;
$datex=date('d', $date).PHP_EOL;
$intmonth = intval($month);
$intdate = intval($datex);
echo $intdate;
echo "<br>";
$sql="INSERT INTO testdata (ID_DATE, EPI_DATE_FEB) VALUES ('','$intdate')";
$result = mysqli_query($conn, $sql);
}
$conn->close();
?>
当我喜欢上面的时候,总共创建了8个id。所以现在我想解决我的问题。告诉我一些解决方案如何解决我的问题。如果你还有困惑那么问我,我也会提供一些细节。
答案 0 :(得分:0)
如果你的表中只有4行且ID_DATE是星期数,你可以在第二个循环中使用UPDATE,如下所示:
// second loop:
$week = $i+1;
$sql="UPDATE testdata set EPI_DATE_FEB = $intdate WHERE ID_DATE=$week";
$result = mysqli_query($conn, $sql);
所以第二个循环可能是:
$number_of_dates = 4;
$startDate_Feb = strtotime("2018-02-01");
for ($i = 0; $i <= $number_of_dates; $i++)
{
$date = strtotime("Monday +" . ($i * 1) . ' weeks', $startDate_Feb);
$month=date('m', $date).PHP_EOL;
$datex=date('d', $date).PHP_EOL;
$intmonth = intval($month);
$intdate = intval($datex);
echo $intdate;
echo "<br>";
$week = $i+1;
$sql="UPDATE testdata SET EPI_DATE_FEB=$intdate WHERE ID_DATE=$week";
$result = mysqli_query($conn, $sql);
}
但使用prepared queries更好。