I have a MySQL database, 'fruits', with 10 rows like this:
id | variable | value
1 | apples | 5
2 | oranges | 6
How can I efficiently use a query to assign PHP variables values, so I can use them elsewhere:
$apples = 5;
$oranges = 6;
Or to put it another way, assign values to PHP variables based on the 'variables' column in the database.
The only way I can make it work is this:
$con = mysqli_connect($servername, $username, $password, $dbname);
$sql="SELECT variable, value FROM fruits where variable = 'oranges'";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$oranges = $row["value"];
I could do this 10 times but it seems terrible, there must be a better way, presumably involving some sort of loop. Not a professional at this (clearly) so complete code so I can see how it all works would be much appreciated.
Thanks for your help!
$fruits[$row['variable']] = $row['value'];, then useecho $fruits['oranges'];(be sure to define the array before entering the loop, to avoid Undefined variable... notices).extract array_column($row, 'value', 'variable');but as @Qirel says, better to work with an array instead