我循环浏览一些数据以显示在我的页面上,然后将每个循环插入数据库中的一行(PHP和MySQL的个人学习练习)。
for
循环运行5次(例如,有时它可能循环更多/更少),并且我能够成功插入前4个循环的数据,但很难搞清楚为什么最后一个循环不会插入数据库。
我的页面上显示所有5个循环迭代,我不太清楚为什么最后一个循环不会插入到数据库中。
这是我的for
循环,其中包含MySQL代码:
$artworksIterations = 1
count($artworksTitle[$x]) = 5
for ($x = 0; $x < $artworksIterations; $x++) {
for ($y = 0; $y < count($artworksTitle[$x]); $y++) {
$savedartworksTitle = $artworksTitle[$x][$y];
echo "TITLE: " . $savedartworksTitle . "<br>";
$savedartworksArtist = $artworksArtist[$x][$y];
echo "ARTIST: " . $savedartworksArtist . "<br>";
$savedartworksYear = $artworksYear[$x][$y];
echo "YEAR: " . $savedartworksYear . "<br>";
$savedartworksMedium = $artworksMedium[$x][$y];
echo "MEDIUM: " . $savedartworksMedium . "<br>";
$implodeGene = implode(", ", $artworksGene[$x][$y]);
echo "GENRES: " . $implodeGene;
$savedartworksDisplay = $artworksDisplay[$x][$y];
echo "<br><img src='" . $savedartworksDisplay . "'><br>";
echo "<br>----<br>";
$sql = "INSERT INTO Artworks (title, artist, year, medium, display, genres) VALUES ('$savedartworksTitle', '$savedartworksArtist', '$savedartworksYear', '$savedartworksMedium', '$savedartworksDisplay', '$implodeGene');";
mysqli_query($conn, $sql);
} // end of y
} // end of x
任何帮助都将深表感谢。谢谢:))
答案 0 :(得分:1)
感谢所有帮助剖析我的问题的人!
事实证明,仅仅巧合的是,每次迭代的最后一个循环中的数据都包含一个撇号(&#39;),这就是为什么它们没有插入到数据库中(语法错误)。
感谢Jacques指出我应该检查错误,这是告诉我语法错误的地方(同样,还要感谢杰夫在我的撇号问题上找到了答案)。
为了解决这个问题,我使用了mysqli_real_escape_string()
函数将数据保存为数据库的安全格式(可能是我应该首先做的事情,学习经验!)。
更新了工作代码:
for ($x = 0; $x < $artworksIterations; $x++) {
for ($y = 0; $y < count($artworksTitle[$x]); $y++) {
// display the information on the web page
echo "TITLE: " . $artworksTitle[$x][$y] . "<br>";
echo "ARTIST: " . $artworksArtist[$x][$y] . "<br>";
echo "YEAR: " . $artworksYear[$x][$y] . "<br>";
echo "MEDIUM: " . $artworksMedium[$x][$y] . "<br>";
echo "GENRES: " . implode(", ", $artworksGene[$x][$y]);
echo "<br><img src='" . $artworksDisplay[$x][$y] . "'><br>";
// save data to MySQL safe format
$savedartworksTitle = mysqli_real_escape_string($conn, $artworksTitle[$x][$y]);
$savedartworksArtist = mysqli_real_escape_string($conn, $artworksArtist[$x][$y]);
$savedartworksYear = mysqli_real_escape_string($conn, $artworksYear[$x][$y]);
$savedartworksMedium = mysqli_real_escape_string($conn, $artworksMedium[$x][$y]);
$savedartworksDisplay = mysqli_real_escape_string($conn, $artworksDisplay[$x][$y]);
$implodeGene = mysqli_real_escape_string($conn, implode(", ", $artworksGene[$x][$y]));
// insert data into database
$sql = "INSERT INTO Artworks (title, artist, year, medium, display, genres) VALUES ('$savedartworksTitle', '$savedartworksArtist', '$savedartworksYear', '$savedartworksMedium', '$savedartworksDisplay', '$implodeGene');";
if (mysqli_query($conn, $sql) === FALSE) {
printf("ERROR: %s\n", mysqli_error($conn));
}
echo "<br>----<br>";
} // end of y
} // end of x