I have these tables in a MySQL database:
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`)
);
I would like to get a table with the users in rows and products in columns, like this question: MySQL Pivot row into dynamic number of columns
In SQL Fiddle (Demo) works fine but I need help to query it from PHP with mysqli.
Is this correct?
$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();
How can I retrieve the data from the query? Execute() method returns TRUE or FALSE.