6

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.

wintercounter
  • 7,500
  • 6
  • 32
  • 46

5 Answers5

9
$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.
alex
  • 479,566
  • 201
  • 878
  • 984
  • I'll accept your answer in 3 minutes, when it allows me. I've did use foreach, but i don't know how to do this with while: – wintercounter Dec 07 '10 at 00:12
  • foreach(mysql_fetch_assoc($quer) as $row => $item) { $arrResults[$row] = $item; } I need this, because i'm using with JSON data, with json_encode function. – wintercounter Dec 07 '10 at 00:13
  • @wintercounter The returned value isn't an array how you want it, so I don't think that will work (it will just loop over the members of the first returned row's array). – alex Dec 07 '10 at 00:24
3

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;
}
Orbling
  • 20,413
  • 3
  • 53
  • 64
2

As documentation http://php.net/manual/en/function.mysql-fetch-assoc.php states:

mysql_fetch_assoc — Fetch a result row as an associative array

So if you want to iterate over result you have to use a loop e.g.:

while ($row = mysql_fetch_assoc($result)) {
    echo $row["title"];
    echo $row["url_title"];       
}
hamczu
  • 1,774
  • 12
  • 14
2

mysqli_fetch_assoc() is functions which is fetching multiple records and displaying through print_r().

$query = "SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5";
$result = mysqli_query($conn,$query);
while(null ! == ($query = mysqli_fetch_assoc($result))){
     print_r($query);
}
Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55
Pooja Khatri
  • 550
  • 5
  • 11
1

the method fetch_assoc() returns one row, you need to loop with it

Freddie
  • 1,717
  • 2
  • 16
  • 23