简体   繁体   English

在动态表中的mysql数据库中添加一行的值

[英]Adding up Values of a row in mysql database in a dynamic table

I have a table with number of fields that change with operation. 我有一个表,其中包含随操作而变化的字段数。 To simplify it to the table below 为了简化到下表

STUDENT MATHS   PHYSICS BIOLOGY TOTAL

PAUL      89      87      65    

JOHN      56      89      54    

The aim is to sum up the scores of each student in the total column. 目的是汇总总计列中每个学生的分数。 I have written a small php code to that effect but is does not given me the result in total. 我已经写了一个小的php代码达到这种效果,但总体上没有给我结果。 I have also tried other variation (which i may not want to post) that did not work. 我还尝试了其他无效的方法(我可能不想发布)。 Any suggestions please. 有任何建议请。

$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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM