Identifying the Issue of MySQL Yielding a Single-Row Result
When executing SQL queries using PHP, sometimes you may encounter a scenario where MySQL only returns a single row, even though the database contains multiple matching records. This can lead to unexpected results and troubleshooting can be challenging.
In the example provided, a PHP script is querying a table named fastsearch for rows where the tags column matches a specific value. However, the code uses the mysql_fetch_assoc() function, which retrieves only the first row of the result set, leading to the display of only one record.
Resolving the Single-Row Retrieval Issue
To rectify this issue and fetch all matching rows from the database, we can modify the PHP code 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); }
Here, we utilize a while loop to iterate over the result set. The mysql_fetch_assoc() function is called within the loop, and it returns the next row each time it is executed. The loop continues until there are no more rows to fetch, displaying all matching records.
The solution addresses two common issues:
The above is the detailed content of Why Does My MySQL Query Only Return One Row in PHP, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!