-1

It's maybe very silly, but I have problem with creating php variables from MySql. To be more clear I have a problem with names of variables!

My code:

<?
$result = $mysqli->query("SELECT * FROM items") or die(mysql_error()); 
$data = array();
while($row = $result->fetch_array())  {
    $data['price' . $row['varname']] = $_row['price'];
//// trying to get set of variables, example:
 $priceitem01 = $row[price]; 
 $priceitem02 = $row[price]; 
 etc....

    $data['name' . $row['varname']] = $row['name'];
//// trying to get set of variables, example:
     $nameitem01 = $row[name];
     $nameitem02 = $row[name];

etc... ?>

Please could you help my here, cause I'm stuck. Tried some solutions with no success and I have a feeling is very basic piece of knowladge. Thanks a lot.

Haza
  • 2,991
  • 1
  • 16
  • 13
Nita
  • 561
  • 5
  • 28

2 Answers2

2

use curly braces '{}'.., see explanation at curly braces ex:

$result = $mysqli->query("SELECT * FROM items") or die(mysql_error());
while($row = $result->fetch_array())  {
   ${'price'.$row['varname']} = $_row['price'];
}

if i assume you field varname values is item01,item02,item03 ... you can print your variables with:

echo $priceitem01;

Community
  • 1
  • 1
check
  • 559
  • 4
  • 12
  • Thank you, works as wanted @check (will look into curly braces - just another good lesson) – Nita Oct 15 '15 at 09:34
0

Here's the cleanest way that I've found to work with a fetched array from the query.By the way, you shouldn't mix MySQL and mysqli functions and you need to reference your connection via $link in the query function.Inside the loop is where you'd want to use extract($row) that way each row is extracted, you can output that row in an echo or assign it to a variable or even use it to perform additional queries.

     $result = $mysqli->query($link, "SELECT * FROM items")
        or die(mysql_error()); 
            $data   = array();
            $names  = array();
            while($row = mysqli_fetch_array($result))  {
                extract ($row);
        Echo $columnyouwanttoecho;
// or if you want to form an array of your own:
$data [$i] = $price;
$names[$i]=$name;
$i++;
     }

Hope that helps!

Jeff
  • 689
  • 1
  • 5
  • 23