我的问题是,当我在浏览器中运行代码时,为什么HW1 / HW2 / HW3列有空白值?
Studentid和Sum列正确显示了代码。任何理想的解决方法?
<?php
$result = mysqli_query($con,"SELECT studentid,SUM(hw1+hw2+hw3)
FROM grade
GROUP BY studentid");
echo "<table border='1'>
<tr>
<th>StudentID</th>
<th>HW1</th>
<th>HW2</th>
<th>HW3</th>
<th>SUM</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['studentid'] . "</td>";
echo "<td>" . $row['hw1'] . "</td>";
echo "<td>" . $row['hw2'] . "</td>";
echo "<td>" . $row['hw3'] . "</td>";
echo "<td>" . $row['SUM(hw1+hw2+hw3)'] . "</td>";
;}
echo "</table>";
mysqli_close($con);
?>
最佳答案
由于未选择列,请尝试:
$result = mysqli_query($con, 'SELECT `studentid`, `hw1`, `hw2`, `hw3`, SUM(`hw1`+`hw2`+`hw3`) as `sum` FROM `grade` GROUP BY `studentid`');
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['studentid'] . "</td>";
echo "<td>" . $row['hw1'] . "</td>";
echo "<td>" . $row['hw2'] . "</td>";
echo "<td>" . $row['hw3'] . "</td>";
echo "<td>" . $row['sum'] . "</td>";
}
关于php - 使用MySQL/PHP对列求和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15722542/