Home > Article > Backend Development > Why Does My MySQL Query Only Return One Row in My PHP Script?
Why MySQL Returns Only One Row in PHP Script
In PHP, you may encounter an issue where a MySQL query only retrieves a single row when you expect multiple results. This discrepancy occurs when using the mysql_fetch_assoc() function incorrectly.
The provided code snippet:
$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5"); $query2 = mysql_fetch_assoc($quer); // Misspelling of $query print_r($query2);
only retrieves the first row from the query result by invoking mysql_fetch_assoc($quer) only once. To fetch all rows, you should use a loop.
The correct code using a loop:
$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5"); while ($row = mysql_fetch_assoc($query)) { print_r($row); }
In this corrected code, note the following:
The above is the detailed content of Why Does My MySQL Query Only Return One Row in My PHP Script?. For more information, please follow other related articles on the PHP Chinese website!