php - Using array to collect data from MySql and creating variables -


i collecting lot of data-strings mysql database. data has used on various different places on website. each string collected database assigned own variable. don't want write same piece of code on , on again. therefore, want use array in order collect strings , create specific variables in process. below have.

    $tablename = "fruits";     $variablesarray = array(                     "apple",                                 "banana",                        "coconut",               );      foreach($variablesarray $val) {       $query = "select * {$tablename} id = '{$val}'";       $result = mysqli_query($conn, $query) or die('error');       while($data = mysqli_fetch_array($result)) {         ($n = 0; $n < 1; $n++){           ${'$val'} = $data["colors"];         }       }       echo ${'$val'};       echo "</br>";     }         

in above, using id's of database in array collects data database. echoes "green", "yellow", "brown".

what however, make 3 variables:

  • $apple = "green"
  • $banana = "yellow"
  • $coconut = "brown"

the above code doesn't create these. unsure of how use ${'$val'} in order achieve this. have tried creating associative arrays well, not able wanted. hoping here point me in right direction. thanks!

your problem (not one) lies in ${'$val'};

single quote strings not parse variables, variable quite literally called '$val'

use $$val

${"$val"}; valid double quote strings parse variables. in simple cases however, unnecessary use quotes, $val string, , unnecessary use curly braces, there no other parts of string want separate variable from.


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -