I got help for a previous problem/question, and just realized that the script I was given returns the “wrong” number/value (yet does not trigger php/mysql errors). Here’s the values:
ingredient #1: 20.216 calories
ingredient #2: 134.4564 calories
The script should return: 154.67 but instead returns: 91.35
The code:
<?php
//The Recipe selected
$recipe_id = $_POST['recipe_id'];
/*****************************************
* Total CALORIES in this recipe
*****************************************/
echo '<h4>Total calories in this recipe:</h4>';
$result = mysql_query(
"SELECT SUM(ingredient_calories), ingredient_amount
FROM recipe_ingredients
INNER JOIN ingredients USING (ingredient_id)
WHERE recipe_id = $recipe_id");
while ($row = mysql_fetch_array($result)) {
$recipe_calories = (
$row['SUM(ingredient_calories)']
* $row['ingredient_amount']);
}
echo number_format($recipe_calories, 2);
mysql_free_result($result);
?>
The ingredients table, stores the default values and serving size for each ingredient.
The recipes table, stores/sets the recipe_id, and other data unrelated to the query)
The recipe_ingredients table, maps the ingredient(s) within a recipe and stores the amount(s) used in the recipe.
I’m sure it’s a problem with the query, but I too wet behind the ears to determine the problem. Any help is greatly appreciated 🙂
UPDATE: Here’s the table data, as requested
ingredients
-----------
ingredient_id
ingredient_name
ingredient_calories
recipes
-------
recipe_id
recipe_name
recipe_ingredients
------------------
recipe_id (fk)
ingredient_id (fk)
ingredient_amount
FIGURED IT OUT!
Made the following adjustments:
Problem solved 🙂