How do I produce a dynamic MySQL pivot table with

2020-02-29 22:00发布

What I have:

I have a table in MySQL named "updates" that currently holds the following information:

enter image description here

What I need:

What I need is the following:

enter image description here

What I have done so far:

I have the following MySQL query that works:

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. Is anyone able to either provide me with the PHP code to perform this or point me in the right direction of information required.

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 mysql mysqli
3条回答
老娘就宠你
2楼-- · 2020-02-29 22:24

The answer is simple. You can always run every query from your set as a separate query() call. 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. As long as the field type is date it cannot do any harm, but for any text type - watch out!

查看更多
一夜七次
3楼-- · 2020-02-29 22:25

This a bit of code how to access to a database with MySQLI if this could help you

<?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"];
        }       
    }
?>
查看更多
▲ chillily
4楼-- · 2020-02-29 22:32

Assuming you are using mysqli (and not PDO) you can't use a simple query() because you want to execute multiple commands. You will need to use multi_query() in combination with store_result(), more_results() and 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();
查看更多
登录 后发表回答