skip to Main Content

I have a table in mysql called site_settings that looks like this

Table in PHPMyAdmin

I am trying to store all of my website settings in mysql and want to pull them into PHP as variables.

I want to pull all values from the variable_name column as the $variable names in PHP and have their values set to whats in the variable_type column.

$site_name = Vexed

$registration_enabled = False

here is my code:

$sql = connect($database_address, $database_username, $database_password, $database);

$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);

while($row = $result->fetch_assoc())
{
  $$row['variable_name'] = $row["variable_type"];
}

$arr = get_defined_vars();
print_r($arr);

the last two lines i am using to see if the variable have been created but i cant get it to work. the best result i have got so far is

    [Array] => Array
        (
            [variable_name] => Vexed
        )

Can anyone tell me where i am going wrong?

Thanks in advance to anyone who can help.

2

Answers


  1. What I think is happening is that when you call $$arr['variable_name'] it’s actually doing $$arr first (which evaluates to $Array after the string conversion), and then trying to assign into assign the [‘variable_name’] key into $Array.

    I would expect this minor modification to work:

    $sql = connect($database_address, $database_username, $database_password, $database);
    
    $query = "SELECT * FROM site_settings";
    $result = $sql->query($query);
    //$row = $result->fetch_all(MYSQLI_ASSOC);
    
    while($row = $result->fetch_assoc())
    {
      $name = $row['variable_name'];
      $$name = $row["variable_type"];
    }
    
    $arr = get_defined_vars();
    print_r($arr);
    

    Edit: I’ll also echo, that it’s a little bit weird to dynamically create variables in this way and it will make your code hard to follow.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search