2

I have a couple of MySQL tables where I run a query on like this:

$sql = "
SELECT my_item 
  FROM t1
     , t2 
 WHERE t1.id='$id' 
   AND t2.spec IN (208, 606, 645) 
   AND t1.spec = t2.spec
";

Note I am using the WHERE IN.

Next I run a query and use WHILE to try to get the results:

$retval = mysql_query($sql) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem = $row['my_item'];
echo "My item is $myitem<br />\n";
} 

This prints three results, each with a different value for $myitem, based on the three options from the IN clause in the SELECT statement at the beginning.

How can I extract and store each of these three values in a separate variable each?

Thank you!

2
  • Wouldn't it be better if $myitem was an array, and then the 'variables' are simply the elements of the array? Commented Nov 26, 2015 at 10:05
  • That sounds like a good idea, Strawberry! To do that, should I use $myitem = array($row['my_item']); ? Commented Nov 26, 2015 at 10:07

2 Answers 2

2

use join

SELECT my_item FROM t1 join t2 
on t1.spec=t2.spec
WHERE t1.id='$id' 
AND t2.spec IN (208, 606, 645)

or create array

while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem[] = $row['my_item'];
}

use this array likt that :-

foreach( $myitem as  $myitems){
echo "My item is $myitems<br />\n";
}

or use indexing

echo "My item is $myitems[0]";
Sign up to request clarification or add additional context in comments.

4 Comments

Will give this a try, Rahautos! My problem, though, is extracting the 3 results in individual PHP variables from the while loop.
Thanks a lot, Rahautos, it woks like a charm!
it's my pleasure :) - @Cucurigu
if my answer helps you please accept my answer @Cucurigu
0

You can store the $row['my_item'] in an array. Refer PHP arrays

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.