Php 公式/查询返回“错误”结果

Php 公式/查询返回“错误”结果,php,mysql,math,Php,Mysql,Math,我在前面的一个问题上得到了帮助,我刚刚意识到,给我的脚本返回了错误的数字/值,但不会触发php/mysql错误。以下是价值观: 成分1:20.216卡路里 成分2:134.4564卡路里 脚本应返回:154.67,但返回:91.35 守则: <?php //The Recipe selected $recipe_id = $_POST['recipe_id']; /***************************************** * Total CALORIES in

我在前面的一个问题上得到了帮助,我刚刚意识到,给我的脚本返回了错误的数字/值,但不会触发php/mysql错误。以下是价值观:

成分1:20.216卡路里

成分2:134.4564卡路里

脚本应返回:154.67,但返回:91.35

守则:

<?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);
?>
你不想这样:

SELECT SUM(ingredient_calories), ingredient_amount
在一列上求和而不是在另一列上求和可能是错误所在。事实上,当我在mysql 5.0.51a中尝试这个查询时,我刚刚得到一个错误

ERROR 1140 (42000): Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no
GROUP columns is illegal if there is no GROUP BY clause
改为这样做:

SELECT SUM(ingredient_calories * ingredient_amount)
并从php中的单个结果行中获取单个列:

$row = mysql_fetch_array($result)
$recipe_calories = $row[0]

这是一个猜测,因为您实际上没有说明问题是什么,但是,结果中的每一行都会覆盖$recipe\u卡路里。也许你的意思是:

$recipe_calories = 0;
while ($row = mysql_fetch_array($result)) {
  $recipe_calories += (
    $row['SUM(ingredient_calories)']
    * $row['ingredient_amount']);
}
尽管您应该在SQL中完成这一切,但无需使用PHP进行计算。

解决了这个问题

作出了以下调整:

$result = mysql_query(
  "SELECT 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['ingredient_calories']
    * $row['ingredient_amount']);
}
echo number_format($recipe_calories, 2);

问题已解决:

您既没有发现输出有什么问题,也没有发现您期望的输出。小johnny tables正在等待他的手。请对您的代码做些什么,因为它很容易受到SQL注入的攻击,所以很容易妥协。您正在从POST获取一个变量,并将其放入SQL查询中,而没有进行适当的清理。您也可以检查,请不要使用mysql_*函数来编写新代码。它们不再得到维护,社区已经开始。看到了吗?相反,你应该学习并使用或。如果你不能决定哪一个,我会帮你的。如果你选择PDO,.@ColeJohnson如果检测到mysql_*应该会自动回复:对不起,伙计们,我想这可能是我语法中的一个简单错误,可以在没有值的情况下发现……但我只是用这些信息编辑了这篇文章。再次感谢!我明白你的意思,但我不明白你认为我应该如何更新脚本。你能发布正确的语法吗?它似乎与之前发布的答案非常相似:选择SumComponent_Carries*Component_amountyea,但它本身不起作用。我不得不使用其他两个答案中的一些变化,以及我自己的调整。
$result = mysql_query(
  "SELECT 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['ingredient_calories']
    * $row['ingredient_amount']);
}
echo number_format($recipe_calories, 2);