Arief Grando Arief Grando - 4 months ago 12
PHP Question

Execute mysql statement via mysql_query

Please help me.

I have mysql query :

SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(mulai = ''',mulai,''', talenta, NULL)) AS ', QUOTE(mulai)) ORDER BY MULAI ASC ) INTO @sql FROM history_talenta;
SET @sql = CONCAT('SELECT nip, nama, DATE_FORMAT(tgl_grade_terakhir,''%d-%m-%Y'') as tgl_grade_terakhir, ', @sql, ' FROM history_talenta GROUP BY nip');
PREPARE stmt FROM @sql;
EXECUTE stmt;


I would like to run it from PHP mysql_query() but nothing appear but when I tried it via phpmyadmin it works and have returned value.

Thank you

Answer

Split into 2 queries:

First query:

SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(mulai = ''',mulai,''', talenta, NULL)) AS ', QUOTE(mulai)) ORDER BY MULAI ASC ) FROM history_talenta; 

Get result of this query from mysql_query into $sql1 variable ,then construct another SQL

$sql2 = "SELECT nip, nama, DATE_FORMAT(tgl_grade_terakhir,'%d-%m-%Y') as tgl_grade_terakhir, " . $sql1 . ' FROM history_talenta GROUP BY nip'; 

Then run mysql_query( $sql2 ) .

Note: mysql_query along with all mysql_* functions is deprecated , I suggest to use mysqli_ functions.