2

我在 MySQL 数据库中有这些表:

CREATE TABLE `product` (
`idProduct` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`category` varchar(255) NOT NULL,
PRIMARY KEY (`idProduct`)
);

CREATE TABLE `sale` (
`idSale` int(10) unsigned NOT NULL AUTO_INCREMENT,
`highDate` date NOT NULL,
`idProduct` int(10) unsigned NOT NULL,
`idUser` varchar(45) NOT NULL,
PRIMARY KEY (`idSale`)
);

我想获得一个表格,其中包含行中的用户和列中的产品,例如这个问题: MySQL Pivot row into dynamic number of columns

SQL Fiddle (Demo)中工作正常,但我需要帮助才能使用 mysqli 从 PHP 查询它。

这个对吗?

$this->dbh->query("SET @sql = NULL");
$stmt = $this->dbh->query("SELECT GROUP_CONCAT(DISTINCT
                          CONCAT(
                          'count(case when category = ''',
                          category,
                          ''' then 1 end) AS ',
                          replace(category, ' ', '')
                       )
                    ) INTO @sql
                FROM product;");

$stmt = $this->dbh->prepare("SET @sql = CONCAT('SELECT s.idUser, ', @sql, ' FROM sale s
                            LEFT JOIN product p ON p.idProduct = s.idProduct
                            GROUP BY s.idUser');");

$stmt->execute();

如何从查询中检索数据?Execute() 方法返回 TRUE 或 FALSE。

4

3 回答 3

0

您可以使用$stmt->fetch$stmt->get_result()从查询语句中检索结果,如下所示:

fetch()

while ($stmt->fetch()) {
    printf ("%s (%s)\n", $name, $code);
}

get_result()

$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
    foreach ($row as $r) {
        print "$r ";
    }
    print "\n";
}
于 2012-10-03T08:10:29.767 回答
0

使用它来获取结果

while ($stmt->fetch()) {
    //code
}

http://php.net/manual/en/mysqli-stmt.fetch.php

于 2012-10-03T08:03:55.020 回答
0

最后我做了以下事情:

$query = $this->dbh->query("SELECT GROUP_CONCAT(DISTINCT CONC...");
$result = array();
$row = $query->fetch_row();

$query = $this->dbh->query("SELECT " . $row[0] . " FROM sale s ...");
return $query->fetch_array(MYSQLI_ASSOC);
于 2012-10-03T13:05:13.630 回答