Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-02 14:43:30
Original
635 people have browsed it

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

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

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!

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