Home >Database >Mysql Tutorial >Why Does My PHP MySQL Query Only Return One Row When Multiple Rows Exist?
In an attempt to retrieve multiple rows from a MySQL table using PHP, you may encounter a situation where only one row is returned, despite having several rows matching your query criteria. This issue can arise due to incorrect code implementation.
In the PHP code provided:
$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5"); $query2 = mysql_fetch_assoc($quer); print_r($query2);
The problem lies within the use of mysql_fetch_assoc($quer). This function only retrieves the first row of the result set and assigns it to $query2. To retrieve all rows matching the query, you need to use a while loop to iterate through the result set.
The corrected code would be:
$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5"); while ($row = mysql_fetch_assoc($query)) { print_r($row); }
This modification assigns each row to the $row variable within the while loop, ensuring the retrieval and display of all matching rows.
The above is the detailed content of Why Does My PHP MySQL Query Only Return One Row When Multiple Rows Exist?. For more information, please follow other related articles on the PHP Chinese website!