Select Data from Mysql and use result as variable in PHP


#1

Im having trouble finding a solution to this. My code below is pulling data from MYSQL successfully. Where I have echoed $weight[‘weight’]."
";, this shows the correct data. As this data is a single piece (decimal number) I want to then use that result from the Mysql query as a variable to use in mathematical sums further into my script. How do I get the data that has been pulled into a variable? Have tried simply “$weight” and “$reuslt4”. Any help much appreciated. Am finding tutorials online contradictory.

$sql4 = “SELECT weight FROM led.panels WHERE panelid = 1”;
$result4 = (mysqli_query($link, $sql4));
while ($weight = $result4->fetch_assoc()) {
echo
$weight[‘weight’]."
";
}


#2

If you don’t have a proper debugger running then you can do this to inspect what your variable really contains

echo '<pre>';
print_r($yourVariableHere);
die();

It should give you a nice printout of what you are working with


In the case above you will either have to do your calculations inside the while loop using $weight[‘weight’]. I’d probably rename it so it would make more sense, remember each row you get is still a panel

$sql = “SELECT weight FROM led.panels WHERE panelid = 1”;
$result = (mysqli_query($link, $sql4));
  while ($panel = $result->fetch_assoc()) {
  echo $panel['weight'];
}

#3

Thats great thanks. Using your arrangement to make it a bit clearer, I have established the variable by:
$weight = $panel[‘weight’];
but still inside the while loop.

Many thanks!