Reputation: 49
I am trying to display SQL table data with PHP, right now I have made an HTML table that infinitely loops up until the end of the page. Now I want to try and display 10~ names vertically before starting a new HTML table next to it that continues looping until the entire SQL table is displayed. The script I have right now is as follows.
$result = mysqli_query($conn, "SELECT name, id FROM table ORDER BY name");
while($row = mysqli_fetch_array($result)){
echo "<table>
<tr><td><input type=\"submit\" name=\"select\" value=\"" . $row['name'] . "\"></input></td></tr>
</table>" ;
}
Upvotes: 0
Views: 52
Reputation: 33247
You can simply fetch all the rows into a table and then split it into chunks of 10.
$result = mysqli_query($conn, "SELECT name, id FROM table ORDER BY name");
$data = $result->fetch_all(MYSQLI_ASSOC);
foreach (array_chunk($data, 10) as $table) {
echo "<table>";
foreach ($table as $row) {
echo "<tr><td><input type=\"submit\" name=\"select\" value=\"" . $row['name'] . "\"></input></td></tr>";
}
echo "</table>";
}
Upvotes: 1
Reputation: 26
if I understood correctly you want to have a table for each 10 rows , if thats the case you can do it as follows :
$result = mysqli_query($conn, "SELECT name, id FROM table ORDER BY name");
$i = 1;
while ($row = mysqli_fetch_array($result)) {
if ($i == 1) {
print "<table>";
} elseif ($i == 10) {
print " </table><table>";
$i = 1;
}
echo "
<tr><td><input type=\"submit\" name=\"select\" value=\"" . $row['name'] . "\"></input></td></tr>
";
$i++;
}
Upvotes: 1