問題描述
我正在嘗試使用 PHP 制作動態表.我有一個頁面顯示數據庫中的所有圖片.我只需要該表為 5 列.如果返回的圖片超過 5 張,則應創建一個新行,其余圖片將繼續顯示.
I'm trying to make a dynamic table with PHP. I have a page which displays all the pictures from a database. I need the table to be of 5 columns only. If more than 5 pictures are returned, it should create a new row and the displaying of the rest of the pics would continue.
有人可以幫忙嗎?
代碼在這里:主頁中的代碼:-
Codes go here: Code in the main page:-
<table>
<?php
$all_pics_rs=get_all_pics();
while($pic_info=mysql_fetch_array($all_pics_rs)){
echo "<td><img src='".$pic_info['picture']."' height='300px' width='400px' /></td>";
}
?>
</table>
get_all_pics() 函數:
The get_all_pics() function:
$all_pics_q="SELECT * FROM pics";
$all_pics_rs=mysql_query($all_pics_q,$connection1);
if(!$all_pics_rs){
die("Database query failed: ".mysql_error());
}
return $all_pics_rs;
此代碼正在創建單行.我想不出如何獲得多行...... !!
This code is creating a single row. I can't think of how I can get multiple rows ... !!
推薦答案
$maxcols = 5;
$i = 0;
//Open the table and its first row
echo "<table>";
echo "<tr>";
while ($image = mysql_fetch_assoc($images_rs)) {
if ($i == $maxcols) {
$i = 0;
echo "</tr><tr>";
}
echo "<td><img src="" . $image['src'] . "" /></td>";
$i++;
}
//Add empty <td>'s to even up the amount of cells in a row:
while ($i <= $maxcols) {
echo "<td> </td>";
$i++;
}
//Close the table row and the table
echo "</tr>";
echo "</table>";
我還沒有測試過,但我的瘋狂猜測是這樣的.只需使用圖像循環瀏覽數據集,只要您還沒有制作 5 個 <td>
,就添加一個.到達 5 后,關閉該行并創建一個新行.
I haven't tested it yet but my wild guess is something like that. Just cycle through your dataset with the images and as long as you didn't make 5 <td>
's yet, add one. Once you reach 5, close the row and create a new row.
這個腳本應該給你類似下面的東西.這顯然取決于您擁有的圖像數量,我假設 5(在 $maxcols 中定義)是您想要連續顯示的最大圖像數量.
This script is supposed to give you something like the following. It obviously depends on how many images you have and I assumed that 5 (defined it in $maxcols) was the maximum number of images you want to display in a row.
<table>
<tr>
<td><img src="image1.jpg" /></td>
<td><img src="image1.jpg" /></td>
<td><img src="image1.jpg" /></td>
<td><img src="image1.jpg" /></td>
<td><img src="image1.jpg" /></td>
</tr>
<tr>
<td><img src="image1.jpg" /></td>
<td><img src="image1.jpg" /></td>
<td> </td>
<td> </td>
<td> <td>
</tr>
</table>
這篇關于用 PHP 創建動態表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!