Select multiple values from the same row? - php

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.

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.

Related

Separate rows from a multi-row result in MySQL PHP

For the code below, $result will return 4 rows from my question_answers table which have the corresponding question_id.
At the moment I am fetching all 4 rows into the $answers variable. I was wondering how I could separate each row from the result and store them as separate variables so I could, say, printf them one at a time.
Thanks.
Edit: also, since the question_id column is an integer in the question_answers table and also in $question["question_id"], have I written my WHERE statement correctly? Thanks.
$result = mysqli_query($connection, 'SELECT FROM questions_answers WHERE question_id='".$question["question_id"]."' ORDER BY RAND()'); //Runs the select query to get the possible answers to the randomly selected question
if(mysqli_num_rows($result)>0){
$answers = mysqli_fetch_assoc($result);
//printf each row individually
}
else{
printf("ERROR: no answers for this question exist!");
}
You can do this like below:
$i=1;
while(${"row" . $i} = mysqli_fetch_assoc($result)){$i++;};
So if there are 4 results, you will get the rows in $row1, $row2, $row3 and $row4;
But more standard way is to save the rows in array and use the array afterwards:
while($rows[] = mysqli_fetch_assoc($result));
In this case, you can access the rows like $rows['0'], $rows['1'], $rows['2'] and $rows['3']

Retrieve last row in array using end($array)

After doing some research I hear that to retrieve the last row on an array I can use end($arrayname)
However when putting this into my page it does not retrieve the last, but the first in the array.
$query2 = "SELECT * FROM Items";
$resultSet2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC))
{
$lastElement = end($row2);
echo $lastElement;
}
Looping through the array like this will loop through and display every row in the array one after the other:
Agate & Labradorite Necklace.jpgAgate Necklace.jpgAventurine, Citrine and Carnelian Necklace.jpg
However I was under the impression it should simply repeat the last item (Carnelian necklace.jpg) every time
$row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC);
$lastElement = end($row2);
echo $lastElement
This will print the first item in the array. Any ideas what is causing this to happen?
Why to do so much trouble just select the last row in the query as
SELECT * FROM Items order by primary_key desc limit 1
primary_key is the column name of your table which is primary key
You are applying end to $row2, which already represents a row of data. This makes $lastElement be the last column of each row (the while iterates over rows).
It would not make sense to fetch N items just so that you can repeat the last one of them N times (in addition: your SQL query does not specify a sort order, so which item is going to be last is also unknown to you). If you wanted to do something like that you would fetch one item using LIMIT 1 and the number N using an appropriate query and finally simply use a for loop.
Try with array_pop function in php
$row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC);
$lastElement = array_pop($row2);
echo $lastElement
you can try this :
$query2 = "SELECT * FROM Items DESC limit 1";
$resultSet2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC))
{
echo $lastElement = $row2;
}

MySQL row selection

I have a table as below,
ID Name Age
----------------------
100 A 10
203 B 20
Now how do i select only row1 using MySQL SELECT command and then I've to increase +1 to it to select row2. In short I'll be using for loop to do certain operations.
Thanks.
Sounds like you've got a mix up. You want to select all the rows you want to iterate through in your for loop with your query, and then iterate through them one by one using php's mysql functions like mysql_fetch_row
You should not try to use tables in a linear fashion like this. Set your criteria, sorting as appropriate, and then to select the next row use your existing criteria and limit it to one row.
SELECT * FROM `table` ORDER BY `ID` LIMIT 1
SELECT * FROM `table` ORDER BY `ID` WHERE ID > 100 LIMIT 1
You'd probably be better off retrieving all rows that you need, then using this. Note the LIMIT is entirely optional.
$query = mysql_query(' SELECT ID, Name, Age FROM table_name WHERE condition LIMIT max_number_you_want '))
while ($row = mysql_fetch_assoc($query)
{
// Do stuff
// $row['ID'], $row['Name'], $row['Age']
}
Lots of small queries to the database will execute much slower than one decent-sized one.
You should get the result into an array (php.net : mysql_fetch_*).
And after you'll can loop on the array "to do certain operations"
Yep, this is a pretty common thing to do in PHP. Like the others who have posted, here is my version (using objects instead of arrays):
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_object($result)) {
// Results are now in the $row variable.
// ex: $row->ID, $row->Name, $row->Age
}

show 2 random rows instead of one

MY SQL QUERY:
$q = mysql_query("SELECT * FROM `ads` WHERE keywords LIKE '%$key%' ORDER BY RAND()");
RESULTS: KEYWORD123
This query searches and results in one random row but i want to show 2 random rows.
How to do that?
any solution?
how??
im grabbing it using this
$row = mysql_fetch_array($q); if ($row
<= 0){ echo 'Not found'; }else{ echo
$row['tab']; }
That query (as-is) will return more than one row (assuming more than one row is LIKE %$key%). If you're only seeing one record, it's possible you're not cycling through the result set, but rather pulling the top response off the stack in your PHP code.
To limit the response to 2 records, you would append LIMIT 2 onto the end of the query. Otherwise, you'll get every row that matches the LIKE operator.
//Build Our Query
$sql = sprintf("SELECT tab
FROM ads
WHERE keyword LIKE '%s'
ORDER BY RAND()
LIMIT 2", ('%'.$key.'%'));
// Load results of query up into a variable
$results = mysql_query($sql);
// Cycle through each returned record
while ( $row = mysql_fetch_array($result) ) {
// do something with $row
echo $row['tab'];
}
The while-loop will run once per returned row. Each time it runs, the $row array inside will represent the current record being accessed. The above example will echo the values stored in your tab field within your db-table.
Remove your order by and add a LIMIT 2
That happens after the execution of the SQL.
Right now you must be doing something like
$res = mysql_query($q);
$r = mysql_fetch_array($res);
echo $r['keywords'];
what you need to do
$q = mysql_query("SELECT * FROM ads WHERE keywords LIKE '%$key%' ORDER BY RAND() LIMIT 2");
$res = mysql_query($q);
while($r = mysql_fetch_array($res)){
echo "<br>" . $r['keywords'];
}
Hope that helps
This query will return all rows containing $key; if it returns only one now this is simply by accident.
You want to add a LIMIT clause to your query, cf http://dev.mysql.com/doc/refman/5.0/en/select.html
Btw both LIKE '%... and ORDER BY RAND() are performance killers

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Categories