0

I currently can print 8 records in one column, I am trying to print 16 records in 2 columns of 8 or 24 in 3 columns of 8. After several months of trying I have to admit it baffles me. Any help or guidance would be greatly appreciated. My code below gives me the first column of 8 perfectly, but after that I am stuck

$result1 = $db->prepare("SELECT * FROM table WHERE id='100' ORDER BY id ASC LIMIT 8 ");

   
$result1->execute();
print("");
$count = $result1->rowCount();
print("");

for($i=0; $row = $result1->fetch(); $i++) {
?>
<body topmargin="0">
<table border="0">
    <tr>  
        <td>        
            <font size="5">ID:<?php echo $row['id']; ?></font><br> 
            <font size="5"><?php echo $row['field1']; ?></font><br> 
            <font size="5">Field1<?php echo $row['field2']; ?></font><br>
            <font size="4">Field2<?php echo $row['field3']; ?></font><br>
            <font size="3">Field3<?php echo $row['field4']; ?></font><br> 
        </td> 
    </tr>
<?php
}
?> 
  • _Small Point_ It is not necessary to use the prepare on a query that has NO parameters – RiggsFolly Jun 25 '20 at 13:18
  • Please complete the code, at least until the end of the for loop – RiggsFolly Jun 25 '20 at 13:21
  • 2
    This is all you got, after “several month of trying”? https://stackoverflow.com/questions/20333961/mysql-php-display-results-in-table-rows-5-results-per-row, https://stackoverflow.com/questions/40561301/loop-row-in-bootstrap-every-3-columns, https://stackoverflow.com/questions/28423210/php-displaying-a-certain-amount-of-records-per-div, https://stackoverflow.com/questions/9099568/array-into-a-table-with-5-cells-in-each-row – CBroe Jun 25 '20 at 13:22
  • `LIMIT 8` - so you only fetch 8 rows... – jibsteroos Jun 25 '20 at 13:23
  • This is all I have that works... not one thing I tried even came close to working. I am not very well versed in PHP - a rank amateur actually - but prefer trying to find a solution before asking for help. The 8 LIMIT is just to show that I can do the first column. I am trying to get more than 8 but in columns. – Joe Soaperowtiz Jun 25 '20 at 14:13

1 Answers1

0

I would approach this by making a loop to output a table with a desired column count.

Within that you will need to iterate a number of rows, and then inside that loop, write out the table entry for each of the columns.

If your data doesn't exactly fill columns x rows then you'll get some blank items of course.

$rows = ceil($count / $columns)
for ($r = 0; $r < $rows; $r++) {
    echo "<tr>";
    for ($c = 0; $c < $columns; $c++) { 
        $value = $result1->getNext() ?? '';
        echo "<td>{$value}</td>";
    }
    echo "</tr>";
}

The getNext() here is up to you of how best to implement. You could load all the values into an array and increment an index counter, or your $db class may give you a more helpful accessor for getting the next value.

Howard Tomlinson
  • 71
  • 1
  • 2
  • 5