I was searching around for a way to implement a crosstab query in MySQL and found an answer from this post show dates in rows as dynamic columns in MySQL. I tried the query and got it to work but how do I write the query in PHP using MySQL procedural style. Below is the query:
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('MAX(IF(`week_start` = "', `week_start`,'", `weekly_value`,0)) AS "',DATE(`week_start`),'"')
) INTO @sql
FROM (SELECT * FROM crosstab WHERE `week_start` BETWEEN NOW() - INTERVAL 4 WEEK AND NOW()) t1;
SET @sql = CONCAT('SELECT s.`ID`, s.`name`, ', @sql, '
FROM (SELECT * FROM crosstab WHERE `week_start` BETWEEN NOW() - INTERVAL 4 WEEK AND NOW()) s
GROUP BY s.`name`
ORDER BY s.`ID`');
SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
$sql = "SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('MAX(IF(`week_start` = "', `week_start`,'", `weekly_value`,0)) AS "',DATE(`week_start`),'"')
) INTO @sql
FROM (SELECT * FROM crosstab WHERE `week_start` BETWEEN NOW() - INTERVAL 4 WEEK AND NOW()) t1;
SET @sql = CONCAT('SELECT s.`ID`, s.`name`, ', @sql, '
FROM (SELECT * FROM crosstab WHERE `week_start` BETWEEN NOW() - INTERVAL 4 WEEK AND NOW()) s
GROUP BY s.`name`
ORDER BY s.`ID`');
SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;";
// echo $sql;
// exit;
$report_query = mysqli_query($conn, $sql);
If I print out the resulting sql and paste it in PHPMyAdmin, the query executes fine but on php in give an SQL syntax error "Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘SELECT GROUP_CONCAT(DISTINCT CONCAT(‘MAX(IF(week_start
=…’ at line 2 in..". Is there a way to write the query in php?
2
Answers
I found a way using mysqli multi_query function :
I just need to work on the array to produce totals. Thank you to all who tried to help.
What about this?