Home  >  Article  >  Backend Development  >  Why Does MySQL Only Return One Row When Using `mysql_fetch_assoc()` in PHP?

Why Does MySQL Only Return One Row When Using `mysql_fetch_assoc()` in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 14:43:30601browse

Why Does MySQL Only Return One Row When Using `mysql_fetch_assoc()` in PHP?

Why MySQL Returns Only One Row in PHP

In MySQL, using PHP's built-in mysql_* functions, a common issue occurs when the expected query result returns multiple rows but only the first row is accessible.

To resolve this, consider the following 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 fetches only the first row of the query result and displays it. To access the remaining rows, a while() loop should be employed:

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

Additional Notes:

  • The original query should be corrected to use mysql_fetch_assoc() correctly, as its return type is a row.
  • The while() loop terminates when mysql_fetch_assoc() returns FALSE, indicating no more rows are available.

The above is the detailed content of Why Does MySQL Only Return One Row When Using `mysql_fetch_assoc()` in PHP?. 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