2

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!

3
  • 3
    You might be looking for variable variables, although in almost every scenario, it's better to use an array instead. Have an array, such as $fruits[$row['variable']] = $row['value'];, then use echo $fruits['oranges']; (be sure to define the array before entering the loop, to avoid Undefined variable... notices). Commented Sep 19, 2016 at 22:30
  • extract array_column($row, 'value', 'variable'); but as @Qirel says, better to work with an array instead Commented Sep 19, 2016 at 22:32
  • do you know the order of the values in db like apple then orange then ... Commented Sep 19, 2016 at 22:35

3 Answers 3

3

Here an example of a Variable-Variable:

$sql="SELECT * FROM fruits";
$result = mysqli_query($conn,$sql);

if ($result->num_rows > 0) {

    while ($row = $result->fetch_assoc()) {
        $variable = $row["variable"];
        $$variable = $row["value"];

        echo("Name: " . ${variable} . " Value: " . $$variable . "<br>");
    }
}

Best regards

Sign up to request clarification or add additional context in comments.

Comments

1

Can use this too.

$con = mysqli_connect($servername, $username, $password, $dbname);

$sql="SELECT variable, value FROM fruits";
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
    ${row["variable"]}= $row["value"];
}

Comments

-1

I can't see a single reason to do so. An array is a variable itself. It's super easy to access any single element with: $rows[2]['variable'] or $rows[1]['value'].

But if you really need some mess you could combine the extract() and a foreach loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.