0

我需要帮助从数据库中获取一些信息。我需要的是从两行中获取信息以作为一个收集,因为我需要为同一主题获取两组标记,所以我拥有的初始代码将是这样的:

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>

现在的问题是并排显示行中的两个结果,因为它最终会成为新行的信息。

4

3 回答 3

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'].

于 2013-05-24T08:58:03.833 回答
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
于 2013-05-24T09:28:30.223 回答
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

有了结果,您应该能够获得一个主题的所有分数的总百分比。

于 2013-05-24T09:00:20.993 回答