繁体   English   中英

使用PHP生成带有MySQL数据的静态单元格计数的HTML表

[英]Use PHP to Generate HTML table with static Cell Count of MySQL Data

我有一个客户,要求我修改其脚本之一以显示已删除的文件名表。 我不允许将mysql修改为mysqli,因为这不是我的网站。

他不是希望将所有内容排成一行并进行分页,而是希望使用列,以便信息可以放在一页上。 我尝试了几种方法,但似乎都无法正常工作

方法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>";

方法2:显示正确的列数,但是在每一行上,它重复一个文件名5x。 (例如,第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>";

(这未经测试,但我认为它将起作用)

经过几天的修改后,我想出了一个解决方案:

// 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.

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