Skip to content Skip to sidebar Skip to footer

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

Solution 1:

$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)


Solution 2:

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

Post a Comment for "Use PHP To Generate HTML Table With Static Cell Count Of MySQL Data"