Home >Database >Mysql Tutorial >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); }
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!