You use the $query variable without initializing it
You use string concatenation with an integer ($i)
(you should use an array instead of concatenation)
You send 6 SELECT queries to the database, but you can fetch everything with a single query, that would be a lot more efficient
Mysqli is outdated and less secured than PDO, you really should use PDO instead.
(for your information, I recently released this PDO database abstraction layer on Github)
Here’s a sample code without PDO to answer your question:
$query = "SELECT draw_date, picknum1, picknum2, picknum3, picknum4, picknum5, picknum6
FROM " . $table_name2 . "
ORDER BY draw_id DESC
LIMIT 20";
$stmt = mysqli_prepare($link, $query);
if (!$stmt) {
echo "Error preparing query: " . mysqli_error($link) . PHP_EOL;
exit;
}
$result = mysqli_execute($stmt);
if (!$result) {
echo "Error executing query: " . mysqli_error($link) . PHP_EOL;
exit;
}
// Fetch all results at once
$rows = mysqli_fetch_all(MYSQLI_ASSOC, $result);
// Close resources
mysqli_free_result($result);
mysqli_stmt_close($stmt);
mysqli_close($link);
if ($rows) {
foreach ($rows as $i => $row) {
echo "**Row " . ($i + 1) . "**" . PHP_EOL;
echo "<pre>";
print_r($row);
echo "</pre>";
}
} else {
echo "No data found in the last 20 drawings." . PHP_EOL;
}