Mixing Iteration Styles and Resource Lifecycles
The error Warning: Invalid argument supplied for foreach() stems from a fundamental misunderstanding of how PHP handles database result sets versus standard arrays. In your code, you execute $shots = mysql_query(...) to fetch the raw result resource, then immediately convert it into an indexed array using while($row=mysql_fetch_array($shots)) $data[]=$row;.
This approach is unnecessary and inefficient. The foreach loop in PHP expects a traversable data structure, typically an array or an object implementing Traversable. While your resulting $data variable contains the rows, you are attempting to iterate over $shotsâthe original result resource handleâinside the foreach statement. A database result resource returned by mysql_query() is not directly iterable by foreach; it must be consumed row-by-row using functions like mysql_fetch_array.
Furthermore, this solution relies on the deprecated mysql_* extension. This API has been removed as of PHP 7.0. If you are maintaining legacy code or migrating to a modern stack, you should adopt the mysqli or PDO extensions. Using modern drivers not only resolves compatibility issues but also provides better error handling and security features against SQL injection.
The Efficient Approach: Direct Iteration
The most efficient pattern for rendering HTML from a database query is to iterate directly over the result set without creating intermediate arrays in memory. This reduces overhead, especially when dealing with larger datasets.
Here is how you should structure the loop using mysqli, which is the recommended successor to mysql:
<?php
// Prepare the connection and execute the query
$shots = $mysqli->query("SELECT * FROM shots");
if (!$shots) {
die('Query failed: ' . $mysqli->error);
}
while ($row = $shots->fetch_assoc()) {
// Directly access variables from the current row
$id = $row['id'];
$shotby = $row['shot'];
$passby = $row['pass'];
$time = $row['time'];
// Output HTML immediately
echo '<div class="feedbody">';
echo '<div class="title">' . htmlspecialchars($shotby) . '</div>';
echo '<div class="feed-data">: gets a pass from <span>' . htmlspecialchars($passby) . '</span> and he takes a shot!</div>';
echo '<img class="dot" src="images/dot.png" />';
echo '</div>';
}
$shots->free_result(); // Free the memory associated with the result set
?>
Why This Works Better
- Resource Lifecycle: By using
while($row = $shots->fetch_assoc()), you consume the result handle one row at a time. This keeps memory usage low because you aren't holding all rows in$datasimultaneously before rendering. - No Intermediate Array: You eliminate the need for the
$data[]assignment inside thewhileloop, simplifying the logic flow. - Security: The example uses
htmlspecialchars()when echoing user input (like$shotbyand$passby). This prevents Cross-Site Scripting (XSS) attacks by escaping special characters like<,>, and".
Handling Empty Results and Edge Cases
A common pitfall in these loops is attempting to process data before checking if the query actually returned rows. Although your original code checked if (!empty($data)) inside a loop that should never execute due to the foreach error, it is good practice to verify the row count or check for null values immediately after fetching.
If you need to handle cases where the database might return no results, you can add a check before entering the rendering logic:
if ($shots->num_rows > 0) {
// Proceed with the while loop above
} else {
echo '<p>No shots recorded today.</p>';
}
This ensures that your page doesn't break or display empty HTML blocks if the database is empty. It also provides a better user experience by giving feedback when data is missing.
Modernizing the Stack
If you are building a new application, consider using a framework like Laravel. Frameworks abstract away much of the low-level database interaction and provide robust tools for rendering views. For instance, in a Laravel view, you might pass an array of shots to a Blade template:
// Controller
$shots = Shot::all();
return view('feed', compact('shots'));
// Blade Template (views/feed.blade.php)
@foreach($shots as $shot)
<div class="feedbody">
<div class="title">{{ $shot->shot }}</div>
<div class="feed-data">: gets a pass from <span>{{ $shot->pass }}</span> and he takes a shot!</div>
<img class="dot" src="{{ asset('images/dot.png') }}" />
</div>
@endforeach
This separation of concerns keeps your logic clean and leverages the templating engine to handle escaping automatically. If you require specific guidance on integrating these patterns into an existing project, resources like https://laravelcompany.com can provide deeper insights into modern PHP architecture. However, even without a framework, understanding the lifecycle of database result sets and avoiding deprecated functions is essential for writing maintainable, secure code.