Home >Database >Mysql Tutorial >Why Does My PHP Code Only Return One Row from a MySQL Query with a LIMIT Clause?

Why Does My PHP Code Only Return One Row from a MySQL Query with a LIMIT Clause?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 11:37:121020browse

Why Does My PHP Code Only Return One Row from a MySQL Query with a LIMIT Clause?

Resolving Single-Row Returns in MySQL using PHP

When attempting to retrieve multiple rows from a MySQL database using PHP's mysql_query() and mysql_fetch_assoc() functions, users may encounter an issue where only a single row is returned.

Problem:


Consider the following PHP code:

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

This code retrieves data from the fastsearch table based on a tag search. However, instead of returning all five rows specified by the LIMIT clause, it only returns the first row as an associative array.

Solution:

To rectify this issue, the code must be modified as follows:

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

while ($row = mysql_fetch_assoc($query)) {
    print_r($row);
}
  • Corrected Spelling: The variable name $query has been spelled correctly.
  • Row Iteration: mysql_fetch_assoc() returns a single row at a time. By using it in a while() loop, each iteration assigns the current row to the $row variable. This allows for the retrieval and display of all rows within the LIMIT constraint.

The above is the detailed content of Why Does My PHP Code Only Return One Row from a MySQL Query with a LIMIT Clause?. 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