简体   繁体   English

如何使用 PHP 生成动态 MySQL 数据透视表?

[英]How do I produce a dynamic MySQL pivot table with PHP?

What I have:我有的:

I have a table in MySQL named "updates" that currently holds the following information:我在 MySQL 中有一个名为“updates”的表,当前包含以下信息:

在此处输入图像描述

What I need:我需要的:

What I need is the following:我需要的是以下内容:

在此处输入图像描述

What I have done so far:到目前为止我做了什么:

I have the following MySQL query that works:我有以下有效的 MySQL 查询:

SET @sql = NULL;

SELECT
  GROUP_CONCAT(DISTINCT
     CONCAT(
       'MAX(IF(Date = ''',
   Date,
   ''', Description, NULL)) AS ',
   CONCAT("'",Date,"'")
 )
   ) INTO @sql
FROM updates;

SET @sql = CONCAT('SELECT Action, ', @sql, ' FROM updates GROUP BY Action');

PREPARE stmt FROM @sql;
EXECUTE stmt;

The actual Question实际问题

I am not able to work out how to execute this using PHP so that I can display this output on a webpage.我无法弄清楚如何使用 PHP 执行此操作,以便可以在网页上显示此输出。 Is anyone able to either provide me with the PHP code to perform this or point me in the right direction of information required.是否有人能够向我提供执行此操作的 PHP 代码或指出我所需信息的正确方向。

I have read a number of articles but I think the issue is that I don't know what I'm actually looking for.我已经阅读了许多文章,但我认为问题在于我不知道我真正在寻找什么。 At first I assumed it was how to run prepared statements within PHP but this didn't appear to help.起初我认为这是如何在 PHP 中运行准备好的语句,但这似乎没有帮助。

Assuming you are using mysqli (and not PDO) you can't use a simple query() because you want to execute multiple commands.假设您使用的是 mysqli(而不是 PDO),您不能使用简单的 query(),因为您想执行多个命令。 You will need to use multi_query() in combination with store_result(), more_results() and next_result().您需要将 multi_query() 与 store_result()、more_results() 和 next_result() 结合使用。

Here is some code I used once:这是我曾经使用过的一些代码:

$db=mysqli_connect($databasehost,$databaseuser,$databasepass,$databasename) or die ("Connection failed!");
$result = $db->multi_query($sql);

if ($err=mysqli_error($db)) { echo $err."<br><hr>"; }

if ($result) {
  do {
  if ($res = $db->store_result()) {
      echo "<table width=100% border=0><tr>";

      // printing table headers
      for($i=0; $i<mysqli_num_fields($res); $i++)
      {
          $field = mysqli_fetch_field($res);
          echo "<td bgcolor=lightgray><b>{$field->name}</b></td>";
      }
      echo "</tr>\n";

      // printing table rows
      while($row = $res->fetch_row())
      {
          echo "<tr>";
          foreach($row as $cell) {
            if ($cell === NULL) { $cell = '(null)'; }
            echo "<td>$cell</td>";
          }
          echo "</tr>\n";
      }
      $res->free();
      echo "</table>";

    }
  } while ($db->more_results() && $db->next_result());
}
$db->close();

This a bit of code how to access to a database with MySQLI if this could help you如果这可以帮助您,这是如何使用 MySQLI 访问数据库的一些代码

<?php
$servername = "hostIP";
$username = "lescours_username";
$password = "password of the data base";
$dbname = "lescoursDB";
 //Create connection
$conn = new mysqli($servername, $username, $password);
 if ($conn->connect_error) {
    echo "La connexion au serveur a etez interompu, Merci d'essayez plus tard";
}else{
    $sql = 'SELECT nom FROM uiotable where nom= \'' . $nom_ut . '\'';
    //$numRows = $result0->num_rows;
    if (!$conn->query($sql)) {
        echo "Nom d'utilisteur incorrecte ";return;
    }else
        {   $result = $conn->query($sql);

        if ($result->num_rows > 0) {
        // output data of each row
            $row = $result->fetch_assoc();
            echo $row["mo_pas"];
        }       
    }
?>

The answer is simple.答案很简单。 You can always run every query from your set as a separate query() call.您始终可以将集合中的每个查询作为单独的 query() 调用运行。 this is universal rule for running multi-query statements.这是运行多查询语句的通用规则。

$mysqli->query('SET @sql = NULL');
$mysqli->query(<<<HERE
SELECT
  GROUP_CONCAT(DISTINCT
     CONCAT(
       'MAX(IF(Date = ''',
   Date,
   ''', Description, NULL)) AS ',
   CONCAT("'",Date,"'")
 )
   ) INTO @sql
FROM updates;
HERE
);
$mysqli->query("SET @sql = CONCAT('SELECT Action, ', @sql, ' FROM updates GROUP BY Action');");
$mysqli->query("PREPARE stmt FROM @sql");

$res = $mysqli->query("EXECUTE stmt");
var_dump($res->fetch_all(MYSQLI_ASSOC));

but please remember that by this kind of query your are essentially running an SQL injection against your own database.但请记住,通过这种查询,您实际上是在对自己的数据库运行 SQL 注入。 As long as the field type is date it cannot do any harm, but for any text type - watch out!只要字段类型是date ,它就不会造成任何伤害,但对于任何文本类型 - 小心!

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

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