What is the issue with the SQL query in the for loop and how can it be resolved?

The issue with the SQL query in the for loop is that it is being executed multiple times unnecessarily, which can impact performance. To resolve this, you can move the SQL query outside of the for loop and fetch all the data at once before looping through the results.

// Issue: SQL query in for loop
// Resolve: Move SQL query outside of for loop

// Connect to database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query outside of for loop
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Fetch all data at once
    $data = $result->fetch_all(MYSQLI_ASSOC);

    // Loop through the results
    foreach ($data as $row) {
        // Process each row
    }
} else {
    echo "0 results";
}

// Close connection
$conn->close();