Correcting Incorrectly Displayed MySQL Rows
Facing an issue where MySQL returns only one row when the expected result should be multiple? Let's explore this PHP code:
<code class="php">$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5"); $query2 = mysql_fetch_assoc($query); print_r($query2);</code>
This code is intended to fetch the first five matching rows from the fastsearch table based on a search query. However, the issue arises due to an incorrect usage of mysql_fetch_assoc.
Using a While Loop to Iterate over Rows
To resolve this, we need to use a while loop to iterate through all the matching rows and display them one by one. Here's the corrected code:
<code class="php">$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5"); while ($row = mysql_fetch_assoc($query)) { print_r($row); }</code>
In this updated code:
Additional Notes:
The above is the detailed content of Why Does My MySQL Query Only Return One Row When I Expect Multiple?. For more information, please follow other related articles on the PHP Chinese website!