Home > Backend Development > PHP Tutorial > Why Does My MySQL Query Only Return One Row When I Expect Multiple?

Why Does My MySQL Query Only Return One Row When I Expect Multiple?

Susan Sarandon
Release: 2024-11-02 17:27:29
Original
510 people have browsed it

Why Does My MySQL Query Only Return One Row When I Expect Multiple?

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>
Copy after login

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>
Copy after login

In this updated code:

  1. The $query variable is correctly spelled.
  2. A while loop is used to iterate over the result set.
  3. $row is assigned the current row using mysql_fetch_assoc inside the loop.
  4. print_r($row) displays the current row each time through the loop.

Additional Notes:

  • Ensure that the MySQL extension is installed and enabled in your PHP configuration.
  • Verify that the $q variable contains the correct search query.
  • Rows are returned in an associative array, where the field names are the keys.
  • The corrected code will display all matching rows up to the specified limit (5 in this case).

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template