0

The following code intends to select a value from a table in a database, use the selected value to change a variable, and then add that variable to another table in the database. However, I cannot figure out why it doesn't work - the $entry query runs, but the application doesn't recognize the $sql query for some reason. Can anyone help me, please?

$sql = "SELECT calories FROM food WHERE name = $food";
$result = $conn->query($sql);

if ($serving_size == 'Plate'){
    $calories = $amount * $result;
}
if ($serving_size == 'Bowl'){
    $calories = $amount * $result * 2/3; 
}

$entry = $conn->prepare("INSERT INTO data (`Food/Exercise`, `Quantity`, `Calories_Burned_or_Consumed`, `Number_of_Calories`) VALUES (?, ?, ?, ?)");
$entry->bind_param("sssi", $food, $quantity, $consumed, $calories);

if($entry->execute()){
    echo 'Inserted';
} else {
    echo 'Not Inserted';
}
Jay Blanchard
  • 33,530
  • 16
  • 73
  • 113
Rohan Jha
  • 11
  • 2

1 Answers1

-1

Is $food actually defined, and is it quoted? If there are no quotes around the string it will be considered a column name here and the query will not match anything.

This query actually is prone to SQL injections, params should be used just like you do below.

Rytis
  • 1,453
  • 1
  • 18
  • 38