我正在尝试使用for循环检索前4个条目,但它似乎重复了1次4次。
这是我的代码:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten");
while($row = mysqli_fetch_array($result)) {
for ($result = 1; $result <= 4; $result++) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
}
mysqli_close($con);
答案 0 :(得分:2)
您不需要 for 循环。我修改了代码,只检索前4项。 查看cahnged查询 LIMIT 4 。
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
?>
答案 1 :(得分:0)
你在while循环中有一个for循环。您可以删除for循环并使用MySQL中的LIMIT
(如果只需要前4个条目,则可以通过PHP获取所有条目(性能更佳)更好):
SELECT * FROM activiteiten LIMIT 4
如果您仍想使用php:
$results = 0;
while($row = mysqli_fetch_array($result) && $results < 4) {
echo "<div class='agenda_item' style='background-color:#F39'>";
...
$results++;
}
答案 2 :(得分:0)
您呈现的代码 - 以与您看到的方式相同的方式混合。不需要for
循环。您应该在MySQL查询中设置LIMIT
,如下所示:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 0,4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
原始代码的问题是for
与while
的混合最终会出现在您展示的场景中,如while
的PHP手册条目中所述:
while语句的含义很简单。它告诉PHP执行 重复的嵌套语句,只要while表达式 评估为TRUE。
所以你有while
迭代结果,但是你也有for
循环嵌套在那里。 100%不必要。
我调整它的方法是删除for
循环,但也将LIMIT 0,4
添加到MySQL查询中。这基本上告诉MySQL从第一行开始获取4行,称为0
。