2012-10-03 218 views
2

我有一個MySQL數據庫中的這些表:爲MySQL準備語句PHP(與mysqli的)

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)工作正常,但我需要幫助從PHP與mysqli查詢它。

這是正確的嗎?

$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。

回答

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); 
0

使用這種用於提取結果

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

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

+0

好的,謝謝!問題是:如何知道列數?要使用'fetch()'我需要在'bind_result($ column1,$ column2,...)'之前完成,但我不知道有多少列檢索查詢。 – Stokres

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"; 
}