Lee Perkins Lee Perkins - 4 months ago 18
PHP Question

PHP while loop output to variables

I have the following loop to get data from a database...

$query = "SELECT id, metal, colour, value FROM data WHERE asset='gold' OR asset='silver' ORDER BY id DESC LIMIT 2";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($result)){
echo $row['metal'] . " is " . $row["colour"] . "<br />";
echo $row['metal'] . " is worth " . $row["value"] . "<br />";
}


which outputs the following:

silver is grey
silver is worth 50
gold is yellow
gold is worth 100


The following:

echo $row['metal'] . " is " .


and...

echo $row['metal'] . " is worth " .


...are simply there for testing and to help explain my issue. How would I go about putting the output into variables like so:

$silverColour = grey
$silverValue = 50
$goldColour = yellow
$goldValue = 100


Many Thanks

Answer

Modify your code this way:

$values = [];
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($result)){
    echo $row['metal'] . " is " . $row["colour"] . "<br />";
    echo $row['metal'] . " is worth " . $row["value"] . "<br />";
    $values[$row['metal']] = $row;
}

Then you can access the values in the $values array:

echo '$silverColour = '. $values['silver']['colour'];
echo '$silverValue = '. $values['silver']['value'];
echo '$goldColour = '. $values['gold']['colour'];
echo '$goldValue = '. $values['gold']['value'];