Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL returns only one row

Tags:

php

mysql

I have this simple PHP code:

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

It only returns this:

Array ( [title] => Kill Bill Vol 1. [url_title] => kill_bill_vol_1 )

I have 3500+ rows in the table, and running the SQL in PhpMyAdmin works perfectly.

like image 471
wintercounter Avatar asked Dec 07 '10 00:12

wintercounter


People also ask

Why does SQL only return one row?

Your select statement includes group_concat() . This is an aggregation function. Because there is no group by , this means that all the rows are treated as one group, and hence one row is returned.

What is limit in MySQL?

The MySQL LIMIT Clause The LIMIT clause is used to specify the number of records to return. The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.


2 Answers

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

while ($row = mysql_fetch_assoc($query)) {
    print_r($row);
}
  • You misspelled $query in your example
  • mysql_fetch_assoc() will return a row each time it is called, and FALSE when out of rows. Use that to your advantage, by assigning a variable to it in the condition. Within the while() loop, $row will be the current row.
like image 164
alex Avatar answered Oct 11 '22 12:10

alex


Right, you are not fetching the results properly.

mysql_fetch_assoc() only returns one row at a time. Use a loop to read all rows.

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

$resultSet = array();
while ($cRecord = mysql_fetch_assoc($query)) {
  $resultSet[] = $cRecord;
}
like image 41
Orbling Avatar answered Oct 11 '22 13:10

Orbling