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.

0

5 Answers 5

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.
Sign up to request clarification or add additional context in comments.

3 Comments

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:
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 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).
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;
}

Comments

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"];       
}

Comments

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);
}

1 Comment

Please give some explanation of this answer
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.