我需要帮助从数据库中获取一些信息。我需要的是从两行收集信息作为一个,因为我需要为同一主题获得两组标记,所以我的初始代码将是这样的:
SELECT scored_mark, total_mark
WHERE student_id ='$_SESSION[user_id]'
AND sub_id=$sid ORDER BY timestamp DESC LIMIT 2
但现在我想要的是获得两者并计算百分比并将它们显示在PHP和HTML表格中,如下所示:
<?php
$first_score = $row['scored_mark'];
$first_total = $row['total_mark'];
$first_mark_percentage = $first_score/$first_total*100
$sec_score = $row['scored_mark'];
$sec_total = $row['total_mark'];
$sec_mark_percentage = $sec_score/$sec_total*100
?>
<table border="1">
<tr>
<th>Subject</th>
<th>1st Mark</th>
<th>2nd Mark</th>
</tr>
<tr>
<td>Maths</td>
<td>$first_mark</td>
<td>$sec_mark</td>
</tr>
</table>
这是表格中的信息:
student_id | sub_id | mark_type | scored_mark | total_mark | timestamp
-----------------------------------------------------------------------
55 | 75 | 4 | 45 | 50 | 13984356
55 | 75 | 4 | 80 | 150 | 13984145
55 | 76 | 4 | 20 | 50 | 13984301
42 | 21 | 3 | 38 | 50 | 13984569
更新:我真正遇到问题的部分是:
<tr>
<td>Maths</td>
<td>$first_mark</td>
<td>$sec_mark</td>
</tr>
问题现在是并排显示行中的两个结果,因为它最终会成为新行的信息。
答案 0 :(得分:1)
您可以在SQL查询中执行此操作。
试试这个:
SELECT scored_mark / total_mark * 100 AS percentage
WHERE student_id = '$_SESSION[user_id]'
AND sub_id = $sid
ORDER BY timestamp DESC
LIMIT 2
结果可以$row['percentage']
访问。
答案 1 :(得分:1)
在处理之前,只需致电mysqli::fetch_assoc()
以获取每一行。
$row = $result->fetch_assoc();
$first_score = $row['scored_mark'];
$first_total = $row['total_mark'];
$first_mark_percentage = $first_score/$first_total*100;
$row = $result->fetch_assoc();
$sec_score = $row['scored_mark'];
$sec_total = $row['total_mark'];
$sec_mark_percentage = $sec_score/$sec_total*100
答案 2 :(得分:0)
您可以尝试使用MySQL SUM()函数。
SELECT
SUM(scored_mark) as score,
SUM(total_mark) as total
FROM
[...]
WHERE
student_id ='$_SESSION[user_id]'
AND
sub_id=$sid
ORDER BY
timestamp DESC
LIMIT
2
根据结果,您应该能够获得一个主题的所有分数的总百分比。