Select multiple values from the same row?
I have a script and I want to return 5 values from the database that ha开发者_Go百科ve 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.
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
}
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
}
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']
}
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
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.
精彩评论