我需要像这样显示来自MySQL的图片:
-------|-------|-------|-------|
Pic 1 | Pic 2 | Pic 3 | Pic 4 |
-------|-------|-------|-------| ----> there can be more then 4 this way>
Pic 5 | Pic 7 | Pic 8 | Pic 9 |
-------|-------|-------|-------|
不能有超过两行,但右边可以有无限数量的列。
我想我需要使用foreach循环。有人有代码会这样做吗?
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT title FROM donuts");
while ($row = mysqli_fetch_assoc($result)) {
for ($x=0; $x<=2; $x++)
{
if($x==0)
{
echo "<tr>";
}
else
{
echo "<td>".$row['title']."</td>";
$x++;
if($x==1) {
echo "</tr>";
}
}
}
}
-------|
pic 1 |
-------|
-------|
pic 2 |
-------|
-------|
pic 3 |
-------|
-------|
pic 4 |
-------|
-------|
pic 5 |
-------|
-------|
pic 6 |
-------|
答案 0 :(得分:2)
此代码将根据结果集的编号自动计算列数。并将它们输出为两行。
$result = array ("Pic 1","Pic 2","Pic 3","Pic 4","Pic 5","Pic 6","Pic 7","Pic 8" );
$rows = 2; // define number of rows
$cols = ceil(count($result)/$rows);// define number of columns
echo "<table border='1'>";
$i=0;
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
for($td=1;$td<=$cols;$td++){
if (isset($result[$i])) {
echo "<td>".$result[$i]."</td>";
$i++;
}
}
echo "</tr>";
}
echo "</table>";
/*
OUTPUT:
-------|-------|-------|-------|
Pic 1 | Pic 2 | Pic 3 | Pic 4 |
-------|-------|-------|-------|
Pic 5 | Pic 6 | Pic 7 | Pic 8 |
-------|-------|-------|-------|
*/