我正在尝试从 MySQL 查询生成 HTML 表。以下是我尝试从 MySQL 查询生成的表的格式:
--------------------------
| Image1 | Image2 | Image3 |
|----------------- --------|
| Name1 | Name2 | Name3 |
|----------------- --------|
| Image4 | Image5 | Image6 |
|----------------- --------|
| Name4 | Name5 | Name6 |
--------------------------
我正在尝试用我的 php 代码创建上面的表格。以下是我的代码,但它无法正常工作,你可以帮助我吗?
include_once("abc.php");
$query=mysql_query("select * from movix LIMIT 6");
echo'<table>';
$i=0;
while($sam=mysql_fetch_array($query))
{
$image = $sam['image'];
$name = $sam['name'];
if($i==0)
{
echo '<tr>';
}
echo '<td>'.' <img src="'.$image.'"/> '.'</td>';
echo '</tr>'; echo '<tr>';
echo '<td>'.$name.'</td>';
echo '<tr>';
if($i==2)
$i=-1;
}
$i++;
}
echo '</table>';
您能否帮助我理解我在代码中做错了什么并为我指出正确的方向?或者请根据我的上表更正我的代码。
最佳答案
表是按行 -> 列从左到右创建的。您正在尝试按列 -> 行、从上到下构建表格。
最简单的方法是将名称放在同一个单元格中,并通过换行符或 div 将其与图像分开
edit 由于您没有在其他地方使用 $image
/$name
变量,因此您可以直接使用它们,并删除 2更多行代码
echo '<table>';
$i=0;
while($sam=mysql_fetch_array($query)) {
if($i%3==0){ // using modulus % to determine if 1st cell
echo '<tr>';
}
echo '<td>'.' <img src="'.$sam['image'].'"/> ';
echo '<br />'.$sam['name'].'</td>'; // echo image name with a line break inside image cell
if($i%3==2){ // using modulus % to determine if 3rd cell
echo '</tr>';
}
$i++;
}
echo '</table>';
如果您仍然希望图像下方的单元格中包含图像名称,一种方法是连接名称,并在第三个单元格后面添加行 -
echo '<table>';
$i=0;
while($sam=mysql_fetch_array($query)) {
if($i%3==0){ // using modulus % to determine if 1st cell
echo '<tr>';
$names = ''; // create image name variable
}
echo '<td>'.' <img src="'.$sam['image'].'"/> '.'</td>';
$names .= '<td>'.$sam['name'].'</td>'; // concat each image name, within a cell
if($i%3==2){ // using modulus % to determine if 3rd cell
echo '</tr>';
echo '<tr>'. $names . '</tr>';
}
$i++;
}
echo '</table>';
关于php - 从 MySQL 查询生成垂直 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24842954/