Home > Database > Mysql Tutorial > Why Does My MySQL Query in PHP Only Return One Row?

Why Does My MySQL Query in PHP Only Return One Row?

Barbara Streisand
Release: 2024-12-01 03:54:11
Original
700 people have browsed it

Why Does My MySQL Query in PHP Only Return One Row?

MySQL Query Returns Only One Row: Debugging and Resolution

When working with MySQL, encountering instances where a PHP script only retrieves a single row can be perplexing. This issue arises when the query itself is valid, but the script's implementation prevents it from retrieving all expected rows.

Troubleshooting the Issue

Consider the PHP code provided, which executes a query to retrieve rows from the fastsearch table:

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

Although the SQL query returns multiple rows, the script shows only one row. This behavior occurs because mysql_fetch_assoc() fetches only a single row by default. To retrieve all the rows, we need to iterate through them using a loop.

Solution: Using while loop to Retrieve Multiple Rows

The corrected code snippet would use a while loop to iterate through the query results and print each row:

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

while ($row = mysql_fetch_assoc($query)) {
    print_r($row);
}
Copy after login

In this updated code, mysql_fetch_assoc() is called within the loop, and the $row variable is assigned the current row. This allows the loop to iterate through each row in the query results, allowing for the printing of all rows.

The above is the detailed content of Why Does My MySQL Query in PHP Only Return One Row?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template