1

Hello I have this code up to now

#issue query  
$query1 = "SELECT ITEM_NAME FROM items_to_buy
ORDER BY ITEM_NAME ASC";


$result1 = mysql_query ($query1)
or die ("Cannot execute query");        

$itemnamesdata = array();     

while ($row = mysql_fetch_array($result1)) 
{
$itemnamesdata[] = $row[0];       
} 

for ($n = 0; $n < count($itemnamesdata); $n++) 

{
$Line = each ($itemnamesdata);

print ("$Line[value].<p>\n");      

}           

  mysql_free_result ($result); 

And it works and gives me all the items in the column : item_name and prints them like so :

Widescreen VA
460W PSU
Router
DSLR Body
Winter Jacket
Smartphone
17-50MM F/2.8 LENS
Colormeter

Now how do I place each results into it's own unique variable?

I want to be able to call them separately like so:

$value1 = Widescreen VA
$value2 = 460W PSU
$value3 = Router
$value4 = DSLR Body
$value5 = Winter Jacket
$value6 = Smartphone
$value7 = 17-50MM F/2.8 LENS
$value8 = Colormeter

Thanks in advance !!!

  • You can use dynamyc variable name : `${'value'.$increment}` – Benjamin Poignant Nov 26 '14 at 16:27
  • 2
    Why do you want to do this? If you have numbered variables like this, then using an array is naturally more appropriate – Mark Baker Nov 26 '14 at 16:27
  • 1
    Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). – Jay Blanchard Nov 26 '14 at 16:28
  • Why two loop ? Put `$Line = each ($itemnamesdata);` `print ("$Line[value].

    \n"); ` in your while ?

    – Benjamin Poignant Nov 26 '14 at 16:32

3 Answers3

1

You would just be able to

echo $itemnamesdata[0];
echo $itemnamesdata[1]; // etc
Gerton
  • 676
  • 3
  • 14
1

In the loop itself you can do this:

$arr = array();
for ($n = 0; $n < count($itemnamesdata); $n++){
  $Line = each ($itemnamesdata);

  print ("$Line[value].<p>\n"); 
  $arr['var_' . $n] = $Line['value'];
}  

extract($arr);
JTG
  • 8,587
  • 6
  • 31
  • 38
Pupil
  • 23,834
  • 6
  • 44
  • 66
0

You can use dynamyc variable name : ${'value'.$increment}

Example :

$increment = 5;

${'value'.$increment} = 'a';

echo $value5;

//echo a
Benjamin Poignant
  • 1,066
  • 8
  • 18