I have a table in mysql called site_settings that looks like this
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
What you’re trying to duplicate is PHP’s extract() builtin function.
It’s generally considered a bad practice, because it will make your code harder for readers to understand or debug.
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:
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.