简体   繁体   English

将SQL查询结果呈现为HTML表

[英]Render SQL query results as an HTML table

I need help rendering data in PHP: 我需要帮助在PHP中呈现数据:

I want to use the results of a SQL query to populate a table, displaying images in a 4-column grid. 我想使用SQL查询的结果来填充表,在4列网格中显示图像。 Here's what I've written so far: 这是我到目前为止所写的内容:

$result = mysql_query("SELECT * FROM gallery ORDER BY id ASC ");

while($row = mysql_fetch_array($result))
{
    echo "<td align=\"center\" ><a href=\"upload_gallery/".$row['image_name']."\" rel=\"prettyPhoto[gallery1]\" title=\" \"><img src=\"upload_gallery/thumbnail/sml_".$row['image_name']."\" width=\"200\" height=\"170\" /></a></td>";
} 
<table><tr>
<?$result = mysql_query("SELECT * FROM gallery ORDER BY id ASC ");
$result =mysql_fetch_array($result)
$count=0;
for($row =0; $row<count($result); $row++)
{
$count++
if($count==4){
echo '</tr><tr>';
$count=0;
}
echo "<td align=\"center\" ><a href=\"upload_gallery/".$row['image_name']."\" rel=\"prettyPhoto[gallery1]\" title=\" \"><img src=\"upload_gallery/thumbnail/sml_".$row['image_name']."\" width=\"200\" height=\"170\" /></a></td>";

} 

?>
</tr>
</table>

You can do a for loop as was suggested by Frederick: 你可以按照弗雷德里克的建议做一个for循环:

$num_rows = mysql_num_rows($result);

for($i = 0; $i < $num_rows; $i++)
{
    // Check if beginning of row
    if($i % 4 == 0)
    {
        //If not the first row, end the last row first
        if($i > 0)
        {
            echo "</tr>";
        }
        echo "<tr>";
    }

    $row = mysql_fetch_assoc($result);
    //Output each individual image
    echo "<td> {*EACH IMAGE code*}</td>";
}

That should give you the idea. 这应该给你的想法。

Try this one: 试试这个:

$arr =array("Test1","Test2","Test3","Test4","Test5","Test6","Test7","Test8","Test9","Test10");
echo "<table><tr>";
for($i = 1 ; $i <= count($arr) ; $i++)
{
    echo"<td>".$arr[$i-1]."</td>";
    $last = $i % 4 == 0? "<tr/><tr>":"";
    echo $last;
}
echo "</table>";

Try this, hope it works for you, 试试这个,希望它适合你,

while($row = mysql_fetch_array($result))
{
$data[]= $row['image_name'];## Pass the image data to new array
} 

$ImagePerRow = 4;### Set the value of image per table row
echo "<table border='1'><tr>";

 foreach($data as $key => $ImageName)
 {
    if(($key+1) == $ImagePerRow)## if key index+1 is equal to ImagePerRow
    {
    echo "<td align=\"center\" ><a href=\"upload_gallery/".$ImageName."\" rel=\"prettyPhoto[gallery1]\" title=\" \"><img src=\"upload_gallery/thumbnail/sml_".$ImageName."\" width=\"200\" height=\"170\" /></a></td></tr><tr>";## then close the table row and start a new table row
    $ImagePerRow+=4;### Add a value of 4 in order to increment the imageperRow value on the next loop
    }else{
    echo "<td align=\"center\" >".$ImageName."</td>";### else echo the normal table data
    }
 }
echo "</tr></table>"; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM