带PHP的MySQL动态数据透视表

时间:2013-01-22 01:00:01

标签: php mysql dynamic pivot

我使用MySQL Workbench运行以下动态数据透视表。但是我有使用PHP执行它的问题。在过去的7天里,我已经尝试过这么多,但它不起作用。需要了解PHP代码应该如何运行。

SET @sql = NULL;
SET group_concat_max_len=15000;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'COUNT(IF(int_supplierid = ',
      int_supplierid,
      ', int_projectid, NULL)) AS NO',
      int_supplierid
    )
  ORDER BY int_supplierid) INTO @sql
FROM tbl_po;
SET @sql = CONCAT('SELECT int_userid, ', @sql, ' FROM tbl_po GROUP BY int_userid');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

我使用的第一个PHP代码;

<?php
require_once('myconn.php');

$approval="SET @sql = NULL;
SET group_concat_max_len=15000;"

$approval3="
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'COUNT(IF(int_supplierid = ',
      int_supplierid,
      ', int_projectid, NULL)) AS NO',
      int_supplierid
    )
  ORDER BY int_supplierid) INTO @sql
FROM tbl_po;
SET @sql = CONCAT('SELECT int_userid, ', @sql, ' FROM tbl_po GROUP BY int_userid');
PREPARE stmt FROM @sql;
EXECUTE stmt;"

$RSFeed2 = mysql_query($approval) or die(mysql_error());
$RSFeed2 = mysql_query($approval3) or die(mysql_error());
$totalRows_RSFeed = mysql_num_rows($RSFeed2);
echo $RSFeed2['int_userid'];
echo $totalRows_RSFeed;
?>

我使用并试过的第二个;

$host="127.0.0.1";
$port=3306;
$socket="";
$user="root";
$password="pwd";
$dbname="kelupis";

$con = new mysqli($host, $user, $password, $dbname, $port, $socket)
    or die ('Could not connect to the database server' . mysqli_connect_error());

//1st query
$query1 = "SET @sql = NULL;
SET group_concat_max_len=15000; SELECT   GROUP_CONCAT(DISTINCT     CONCAT('COUNT(IF(int_supplierid = ',int_supplierid,', int_projectid, NULL)) AS NO',int_supplierid)   ORDER BY int_supplierid) INTO @sql FROM tbl_po;";


if ($stmt = $con->prepare($query1)) {
    $stmt->execute();
    $stmt->bind_result($int_supplierid);
    while ($stmt->fetch()) {
        printf("%s\n", $int_supplierid);
    }
}

1 个答案:

答案 0 :(得分:0)

PHP的mysql API不支持多查询。

换句话说,您无法准备和执行包含由分号分隔的多个SQL语句的字符串。

同样,mysqli不支持使用普通的mysqli :: query()函数进行多查询。您必须使用mysqli::multi_query()

但是多查询是really a bad idea。你应该坚持逐个执行语句。

PS:从PHP 5.3.0开始,mysql扩展名为deprecated anyway,因此您应该在任何新代码中使用mysqli或PDO。


我从您的示例中看到您正在尝试进行动态调整。您希望每个supplierid都有一列,并且该列的值应该是该supplierid的计数。

将这些计数输出为而不是列更简单,更有效:

$query = "SELECT int_supplierid, COUNT(int_projectid) 
    FROM tbl_po GROUP BY int_supplierid";

if (!($stmt = $con->prepare($query))) {
    die($con->error);
}
if (!$stmt->execute()) { 
    die($stmt->error); 
}
$stmt->bind_result($int_supplierid, $no);
while ($stmt->fetch()) {
    printf("%s: %d\n", $int_supplierid, $no);
}