1

I have a script and I want to return 5 values from the database that have the same category but it is only returning one. Any ideas?

Here's the script:

 $result = mysql_query("SELECT Category FROM GameData
        WHERE Title=\"$title\" ");
//returns category to search in next select
    $row= mysql_fetch_array($result);
    $results = mysql_query("SELECT Title FROM GameData
    WHERE Category=\"$row[0]\" LIMIT 5 ");
    $rows= mysql_fetch_array($results);
    print_r($rows); //returns $title from first select query

I'm new to databases and MySQL so any help would be much appreciated.

2
  • 1
    I would suggest you use something like PHP PDO instead of mysql_x. It's newer, provides db abstraction and with prepared statements you can prevent sql injection Commented Feb 26, 2011 at 17:23
  • Your code is unfortunately not efficient, if you are new to databases, learn them from beginning in right way. Use join's. Commented Feb 26, 2011 at 17:27

5 Answers 5

4

mysql_fetch_array just fetch one row in one call use loop to fetch multiple records

while($row= mysql_fetch_array($results))
{

    print_r($row); //returns $title from first select query
}
Sign up to request clarification or add additional context in comments.

Comments

3

You must loop over all the results: mysql_fetch_array returns one result row, so you have to call it multiple times:

while($row = mysql_fetch_array($results)) {
    // here process ONE row
}

1 Comment

Thanks a ton. Thought it might be something with a loop but haven't used any loop in php other than the for loop so didn't know what to use. Thanks again :)
1

mysql_fetch_array will only fetch one row : if you want to fetch several rows, you'll have to call mysql_fetch_array several times -- in a loop, typically.


For a couple of examples, you can take a look at its manual page ; but, in your case, you'll probably want to use something like this :

$results = mysql_query("SELECT Title FROM GameData
    WHERE Category='...' LIMIT 5 ");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
    // work with $row['Title']
}

Comments

1

mysql_fetch_array only returns one row, you would have to loop through the rows

see example at: http://php.net/manual/en/function.mysql-fetch-array.php

Comments

1

You should use following query in order to make things right.

 SELECT `Title` FROM GameData 
 LEFT JOIN
 Category ON Category.Id = GameData.Category
 WHERE Category.Title = "$title" LIMIT 5

I assumed that Category has column Id.
I advise you to learn about JOINS.
Additionally, you may want to rename Category to Category_Id, and drop letter-case so Category would become category_id.

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.