Home > Backend Development > PHP Tutorial > Why is my MySQL query only returning one row when executed in PHP?

Why is my MySQL query only returning one row when executed in PHP?

Susan Sarandon
Release: 2024-11-03 08:35:02
Original
568 people have browsed it

Why is my MySQL query only returning one row when executed in PHP?

MySQL Only Returning One Row from a Query

Problem:

When executing a SQL query that should return multiple rows, only one row is being retrieved using PHP's mysql_query() and mysql_fetch_assoc(). The SQL query executed directly in PhpMyAdmin returns all expected rows.

Solution:

Option 1: Using a Loop to Iterate Over Rows

$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
  • This code uses a while loop to iterate over all rows returned by the query.
  • Each row is assigned to the $row variable and can be accessed within the loop.

Option 2: Using mysql_fetch_array() to Retrieve an Array of Rows

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

$rows = array();
while ($row = mysql_fetch_array($query)) {
    $rows[] = $row;
}
Copy after login
  • This code uses mysql_fetch_array() to retrieve an array of rows.
  • The $rows array will contain an array for each row returned by the query.

Note:

  • The problem occurred because mysql_fetch_assoc() only returns one row at a time.
  • The misspelled variable name $quer instead of $query may have also contributed to the issue.

The above is the detailed content of Why is my MySQL query only returning one row when executed in PHP?. 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