2015-08-14 45 views
0

我有一個表格,其中的字段數隨操作而變化。將其簡化爲如下表格在動態表中添加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; 
} 
?> 
+0

見正常化。數據庫表格不是電子表格。 – Strawberry

回答

0

您的查詢應該是這樣的

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

謝謝,這隻會有效,只是這些字段是動態的,並會隨着操作而改變,說另一個課程「語言」將被添加。每次發生這種情況時,我都不希望更改代碼 – Jomaz

相關問題