Matt
Matt

Reputation: 55

Select multiple values from the same row?

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.

Upvotes: 1

Views: 976

Answers (5)

mailo
mailo

Reputation: 2611

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.

Upvotes: 1

Deep Kapadia
Deep Kapadia

Reputation: 1458

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

Upvotes: 1

Shakti Singh
Shakti Singh

Reputation: 86336

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
}

Upvotes: 4

ChrisJ
ChrisJ

Reputation: 5251

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
}

Upvotes: 3

Pascal MARTIN
Pascal MARTIN

Reputation: 400922

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']
}

Upvotes: 1

Related Questions