php - 将mysql数据库中的一行值添加到动态表中

标签 php mysql

我有一个表,其中的字段数量随着操作而变化。将其简化为下表

STUDENT MATHS   PHYSICS BIOLOGY TOTAL

PAUL      89      87      65    

JOHN      56      89      54    

目的是将每个学生的分数相加到总列中。我已经为此编写了一个小的 php 代码,但并没有给出总体结果。我还尝试了其他不起作用的变体(我可能不想发布)。如有任何建议,请。

$table = 'scores';
$total = '';
$result = mysql_query("SELECT * FROM $table");

if (!$result) {
    die("Query to show fields from table failed");
}

$fields_num = mysql_num_fields($result);
//table to display student scores 
echo "<table><tr>";

for ($i=0; $i<$fields_num; $i++) {
   $field = mysql_fetch_field($result);
   echo "<th>$field->name</td>";
} 

echo "</tr>\n";

while ($row = mysql_fetch_object($result)) {
    $student_id=$row->student_id;
    echo "<tr>";
    foreach($row as $cell) {
        echo "<td> $cell </td>";
    }
    // calcuate the total score of each record
    $total =($cell + $total);
    echo "</tr>\n";
    echo 'The total = '.$total;
}

// functio to insert the total scores t the table
function tScore($table, $student_id, $total) {
    $sqlCommand = "UPDATE $table SET total='$total' WHERE student_id='$student_id' "; 
    $query = mysql_query($sqlCommand) or die ('Sorry something went wrong while inserting Subjects Scores'); 

    return $total;
    return $student_id;
}
?>

最佳答案

您的查询应该是这样的

$sel="select *,(sum(Maths)+sum(Physics)+sum(Biology)) as Total from sum group by Student";

关于php - 将mysql数据库中的一行值添加到动态表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32016321/

相关文章:

javascript - 当服务器端脚本可以轻松做到这一点时,为什么浏览器不允许 CORS?

MySQL 错误 1415 (0A000) : Not allowed to return a result set from a function

php搜索帮助

php - 我是否必须从 Laravel 中每个 Controller 的数据库中返回 header 数据?

php - Mysql 使用特殊字符搜索匹配查询

php - 上传文件到服务器时在MySQL数据库中保存文件路径

mysql - 用零填充缺失的行

python将特殊字符转换为转义字符

mysql - 发电机 : How to call dynamodb api from ZF2 rest application

php - MySQL 到 MySQL 克隆与 PHP