简体   繁体   English

使用PHP从MySQL数据库跨多列格式化结果

[英]Formatting results across multiple columns from MySQL database with PHP

I am looking for a way to display data from a MySQL database across multiple columns in a similar fashion to a spreadsheet. 我正在寻找一种以类似于电子表格的方式跨多个列显示MySQL数据库中数据的方法。

I have not started the table design as yet as I am unsure of the best approach to achieve what I would like. 我还没有开始表格设计,因为我不确定实现我想要的最佳方法。

I have considered the following: 我考虑了以下内容:

TABLE 1 - Homework Task

id (INT)

task (VARCHAR)

This table is just a list of homework tasks 该表只是家庭作业的列表

TABLE 2 - Students

id (INT)

studentName (VARCHAR)

This is just a list of students 这只是学生名单

TABLE 3 - Homework Grades

id (INT)

homeworkTaskId (INT)

studentId (INT)

grade (VARCHAR)

percentage (DECIMAL)

This will hold the marks for each homework task for each student 这将为每个学生保留每个作业的分数

Now, what I would like to achieve is to be able to display the data like this: 现在,我想要实现的是能够显示如下数据:

在此处输入图片说明

What I am struggling with is my knowledge of SQL commands and knowing if it is possible to retrieve the data in such a way that I can loop through it to display in this format? 我正在苦苦挣扎的是我对SQL命令的了解以及是否有可能以一种可以循环浏览以这种格式显示的方式来检索数据?

I am using PHP with a PDO connection to the MySQL database. 我将PHP与PDO连接使用到MySQL数据库。

Many thanks in advance for any possible assistance in this matter. 在此先感谢您提供任何可能的帮助。

I would use 2 queries, it's much simpler and if your looking it up by the foreign key ( student.id ) in the homework table, it should be fast enough where performance wont be an issue. 我将使用2个查询,它要简单得多,并且如果您通过作业表中的外键(student.id)查找它,它应该足够快,而性能不会成为问题。

   $DB = new PDO('mysql:host='.$conf['dbhost'].';dbname='.$conf['dbname'], $conf['dbuser'], $conf['dbpass']);

   $students_stmt =  $DB->query('SELECT * FROM students');

   $homework_stmt = $DB->prepare('
       SELECT
            h.id, h.grade, h.percentage, ht.task 
       FROM
            homework AS h
       JOIN
            homework_task AS ht
       ON
          ht.id = t.homeworkTaskId
       WHERE
           h.studentId = :student_id
   ');


   $data = [];

   $max_homework = 0; //maximum number of homework records

   while( false !== ( $student = $students_stmt->fetch(PDO::FETCH_ASSOC) )){

       $homework_stmt->execute([':studentId'=>$student['id']]);

       $i = 1;
       while( false !== ( $homework = $homework_stmt->fetch(PDO::FETCH_ASSOC) )){
          $student["homework_$i"] = $homework;
          ++$i;
       }
       if( $i > $max_homework )  $max_homework = $i;

       $data[] = $student;
   }

You'll wind up with an array like this 您将获得像这样的数组

 $data = [ 0 =>   //first student
     [
        'studentName' => 'Some Guy',
        'homework_1' => [
            'grade' => 'A',
            'percentage' => '92'
        ],
        'homework_2' => [
            'grade' => 'B',
            'percentage' => '85'
        ]
        'homework_3' => [ .... ]
     ], 1 => [ ... //second student ]
  ];

Then you can loop over $data and create the table 然后,您可以遍历$data并创建表

The $max_homework is because when you go to display it you will need to know how many homework columns you need ( [group, percentage] ) that way you can create the proper number of headers in your table and fill the students that have less then that. $max_homework是因为当您显示它时,您将需要知道您需要多少个作业列([group, $max_homework ]),这样您才能在表中创建适当数量的标题并填充少于该数量的学生那。 So each row in the table has the same number of cells, if that makes sense. 因此,如果可以的话,表格中的每一行都有相同数量的单元格。 That is if the number of homework records vary from student to student. 那就是如果作业记录的数量因学生而异。

By the way this code is untested as I have no way to know the full schema of your tables. 顺便说一下,此代码未经测试,因为我无法知道表的完整架构。 It's just an example of the simplest approach ( using PDO ). 这只是最简单方法(使用PDO)的一个示例。

This is an example from the php documentation that should get you started. 这是php文档中的示例,应该可以帮助您入门。 $row will take on the names of the fields in the database because we chose result->fetchassoc $ row将采用数据库中字段的名称,因为我们选择了result-> fetchassoc

<?
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT * FROM table ORDER by ID";

if ($result = $mysqli->query($query)) {

/* fetch associative array */
while ($row = $result->fetch_assoc()) {
    echo "<div>".$row['studentname']."</div>";
    echo "<div>".$row['studentgrade']."</div>";
}

/* free result set */
$result->free();
}

/* close connection */
$mysqli->close();
?>

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

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