[英]Use PHP to Generate HTML table with static Cell Count of MySQL Data
I have a customer who has asked me to modify one of their scripts to display a table of file names that have been deleted. 我有一个客户,要求我修改其脚本之一以显示已删除的文件名表。 I am not allowed to modify mysql to mysqli as this is not my site. 我不允许将mysql修改为mysqli,因为这不是我的网站。
Rather than putting them all in a line and paginating, he wants columns so that the information can fit on one page. 他不是希望将所有内容排成一行并进行分页,而是希望使用列,以便信息可以放在一页上。 I have tried several methods but none seem to work properly 我尝试了几种方法,但似乎都无法正常工作
Method 1: Displays the correct number of columns, but repeats the same file name in every cell: 方法1:显示正确的列数,但在每个单元格中重复相同的文件名:
$q = "SELECT `name` FROM `files` WHERE `deleted` = 1";
$r = mysql_query($q);
$rows = mysql_num_rows($r);
$deleted = mysql_fetch_assoc($r);
// Build table and iterate through the results
$end = $rows; // total # of results
$t_rows =ceil($end/5); // number of cells per row
$x = 0;
$start = 0;
echo "<table>";
while($x <= $t_rows){
echo "<tr>";
for($y = 0; $y < 5; $y++, $start++){
if($start <= $end){
echo "<td>".$deleted['name']."</td>";
}
}
echo "</tr>";
$x++;
}
echo "</table>";
Method 2: Displays the correct number of columns, but on each row it repeats a file name 5x. 方法2:显示正确的列数,但是在每一行上,它重复一个文件名5x。 (Example, Row 1 has the name of the first record 5 times, Row 2, the name of the 2nd file, etc). (例如,第1行的名称是第一个记录的5倍,第2行的名称是第2个文件的名称,依此类推)。
$q = "SELECT `name` FROM `files` WHERE `deleted` = 1";
$r = mysql_query($q);
$rows = mysql_num_rows($r);
// Build table and iterate through the results
$end = $rows; // total # of results
$t_rows =ceil($end/5); // number of cells per row
$x = 0;
$start = 0;
echo "<table>";
while($x <= $t_rows){
echo "<tr>";
while($deleted = mysql_fetch_assoc($r)){
for($y = 0; $y < 5; $y++, $start++){
if($start <= $end){
echo "<td>".$deleted['name']."</td>";
}
}
echo "</tr>";
$x++;
}
}
echo "</table>";
$q = "SELECT `name` FROM `files` WHERE `deleted` = 1";
$r = mysql_query($q);
// Build table and iterate through the results
$cols = 5; //number of columns
$x = 0;
echo "<table>";
while($deleted = mysql_fetch_assoc($r)){
if($x % $cols == 0) echo '<tr>'; // when $x is 0, 5, 10, etc.
echo "<td>".$deleted['name']."</td>";
if($x % $cols == $cols-1) echo "</tr>"; // when x is 4, 9, 14, etc.
$x++;
}
if($x%$cols!=0) echo "</tr>"; // add a closing </tr> tag if the row wasn't already closed
echo "</table>";
(This is untested, but I think it'll work) (这未经测试,但我认为它将起作用)
After tinkering with this the last few days I've come up with a solution: 经过几天的修改后,我想出了一个解决方案:
// Build table and iterate through the results
$int = 1;
echo "<table>";
while($deleted = mysql_fetch_assoc($r)){
if($int%5==1){
echo "<tr>";
}
echo "<td>".htmlspecialchars($deleted['name'])."</td>";
if($int%5==0){
echo "</tr>";
}
$int++;
}
echo "</table>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.