以下代码提供了以下信息:
$getexpenses = "SELECT sum(expense_amount) FROM projects_expense WHERE project_id=$project_id";
$showexpenses = @mysqli_query ($dbc, $getexpenses); // Run the query.
echo ' . $showexpenses . ';
给我一个结果
' . $showexpenses . '
而不是实际的总和。。。
我肯定我错过了一些简单的事情。。。谢谢!
最佳答案
我添加了对mysqli_fetch_assoc($showexpenses)
的调用以使其完全正常工作。
我还清理了$project_id
以避免注入,并使用别名通过关联数组访问sum。
$getexpenses = "SELECT SUM(`expense_amount`) as `sum_amount` FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_assoc($showexpenses);
$sum = $sums['sum_amount'];
echo $sum;
我们也可以这样使用
mysqli_fetch_row
:$getexpenses = "SELECT SUM(`expense_amount`) FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_row($showexpenses);
$sum = $sums[0];
echo $sum;
不再需要别名,因为我们知道第一列(0)是匹配的。
注意:如果您想使用
GROUP BY project_id
关于php - 如何用PHP回显此MySQL命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5809255/