Home  >  Article  >  Backend Development  >  Why Does My MySQL Query Only Return One Row in My PHP Script?

Why Does My MySQL Query Only Return One Row in My PHP Script?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 14:47:03237browse

Why Does My MySQL Query Only Return One Row in My PHP Script?

Why MySQL Returns Only One Row in PHP Script

In PHP, you may encounter an issue where a MySQL query only retrieves a single row when you expect multiple results. This discrepancy occurs when using the mysql_fetch_assoc() function incorrectly.

The provided code snippet:

$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5");
$query2 = mysql_fetch_assoc($quer); // Misspelling of $query
print_r($query2);

only retrieves the first row from the query result by invoking mysql_fetch_assoc($quer) only once. To fetch all rows, you should use a loop.

The correct code using a loop:

$query = mysql_query("SELECT `title`,
                             `url_title`
                        FROM `fastsearch`
                       WHERE `tags`
                            LIKE '%$q%'
                       LIMIT 5");

while ($row = mysql_fetch_assoc($query)) {
    print_r($row);
}

In this corrected code, note the following:

  1. The $query variable is spelled correctly.
  2. The while loop assigns each row returned by mysql_fetch_assoc($query) to the $row variable.
  3. Within the loop, you can access and print each row's data using $row.

The above is the detailed content of Why Does My MySQL Query Only Return One Row in My PHP Script?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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