简体   繁体   English

查询结果在PHP / HTML显示中显示不需要的SQL SUM公式文本

[英]Query result shows unwanted SQL SUM formula text in PHP/HTML display

I have a table 'marks' with fields Q1mark, Q2mark, Q3mark . 我有一个带有字段Q1mark,Q2mark,Q3mark的表“ marks”。 . . Q50mark corresponding to the 50 questions in an exam. Q50mark对应于考试中的50个问题。

I want to display how many marks each question attracted, and I'd like to order the questions by difficulty. 我想显示每个问题吸引了多少分,我想按难度对问题进行排序。

So I loop through 50 and put the key=>value pairs in a HTML table: 因此,我遍历了50个,并将key => value对放入HTML表中:

for ($i=1; $i<=50; $i++)
 {

        $stmt = $db->prepare("SELECT (SUM(Q".$i."mark)) FROM marks");
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

      foreach ($results as $result) 
          { 
            echo '<tr>';
            foreach ($result as $key=>$value)
                  { 
                echo '<td>'; echo $key; echo '</td>';
                echo '<td>'; echo $value; echo '</td>';

              } 
        echo '</tr>';
              }   
    }

What I get is: 我得到的是:

------------------------
| (SUM(Q1mark)) |   18 |
| (SUM(Q2mark)) |   20 |
| (SUM(Q3mark)) |   8  |
| (SUM(Q4mark)) |   12 |
------------------------

but what I want is: 我想要的是:

----------------
| Q3mark |  8  |
| Q4mark |  12 |
| Q1mark |  18 |
| Q2mark |  20 |
----------------

How do I get rid of the displayed formula text?, And order the data by difficulty? 如何摆脱显示的公式文本?,并按难度对数据进行排序?

One way to do this is to store all the result in a 2d array. 一种方法是将所有结果存储在2d数组中。

$final_result = array();
for ($i=1; $i<=50; $i++)
 {

        $stmt = $db->prepare("SELECT (SUM(Q".$i."mark)) FROM marks");
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
       $final_result[] = $results;

 }
sort($final_result);
for($i=0;$i<count($final_result);$i++){
    echo $final_result[$i][“Q”.$i.”mark”];
}

Have a look at sorting arrays in PHP https://www.w3schools.com/php/php_arrays_sort.asp 看看PHP中的排序数组https://www.w3schools.com/php/php_arrays_sort.asp

I'll close this question with an answer to the question posed in the question title that was supplied in a comment, otherwise it'll appear unanswered. 我将用注释中提供的问题标题中提出的问题的答案来结束该问题,否则它将显示为未回答。

To get of the SUM formula text I need to SELECT the result AS . 要获得SUM公式文本,我需要选择结果AS。 . . and use the variable $i in the column name: 并在列名称中使用变量$ i:

(SUM(Q".$i."mark)) AS Q$i

I'll open a new question with a tighter focus on the other problem I mentioned, namely ordering the query results. 我将打开一个新问题,重点放在我提到的另一个问题上,即对查询结果进行排序。

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

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