Short
Generating table with barcodes of items. Each item has exact quantity in database table. Fields in tables are limited: 65, if more then 65 then build a second table, then a third one…How to generate tables with this conditions?

Detailed
Let’s say we want to generate a table with 65 available fields (5×13).
My plan is the following
- User selects items’ checkboxes
- When user submits form, PHP gets values of checked checkboxes
- PHP gets quantities of each item from database
- Generating table
For ex. the quantity for item id 55 is 2 and for 56 is 4 then the table must look like that

My code looks like that (I know that it’s wrong, but I can’t figure out how it must be. There must be more than 5 counters: rows counter, columns counter, $_POST[‘id’] counter, items’ quantity counter, table counter (if total sum is more than 65))
UPDATE
<?php
$items = array();
foreach ($_POST['checkbox'] as $id) {
$stmt = $db->prepare("SELECT `qt` FROM `items` WHERE `id`=?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($qt);
$stmt->fetch();
$stmt->close();
for ($cnt = 1; $cnt <= $qt; $cnt++)
$items[] = $id;
}
$i = 0;
foreach ($items as $item) {
for ($j = 0; $j < $item['quantity']; $j++) {
// check if it's the beginning of a new table
if ($i % 65 == 0)
echo '<table>';
// check if it's the beginning of a new row
if ($i % 5 == 0)
echo '<tr>';
echo '<td><img src="bc.php?id=' . $item['id'] . '" alt="' . $item['name'] . '" /></td>';
// check if it's the end of a row
if (($i - 1) % 5 == 0)
echo '</tr>';
// check if it's the end of a table
if (($i - 1) % 65 == 0)
echo '</tr></table>';
$i++;
}
}
// if the last row wasn't closed, close it
if ($i % 5 != 0)
echo '</tr>';
// if the last table wasn't closed, close it
if ($i % 65 != 0)
echo '</table>';
?>
Any suggestion?
EDIT 4