0

I am using mysql database with tool adminar and I want to convert data from one table to column and get it in json object. I have the table in following format-

----------------------------------------------------
| prn | finding_field | finding_value | finding_no |
----------------------------------------------------
|  3  | Temperature   |   100         |    1       |    
|  3  | Fasting       |   99          |    1       |    
|  3  | Random        |   120         |    1       |     
|  6  | Temperature   |   98          |    2       | 
|  6  | cholesterol   |   200         |    2       |
----------------------------------------------------

and my expected output is as follows-

-------------------------------------------------------------
| finding_no | Temperature | Fasting | Random | cholesterol |
-------------------------------------------------------------
|    1       |    100      |  99     |  120   |   NULL      |
|    2       |    98       |  NULL   |  NULL  |   200       |
-------------------------------------------------------------

I have written the query as follows-

  SET @sql = NULL;
        SELECT
          GROUP_CONCAT(DISTINCT
            CONCAT(
              'GROUP_CONCAT(IF(finding_field = ''',
              finding_field,
              ''',finding_value, NULL)) AS ',
              finding_field
            )
          ) INTO @sql;
        SET @sql = CONCAT('SELECT finding_no                  
                            , ', @sql, ' 
                           FROM cpc_specific_finding 
                           where prn=3 
                           GROUP BY finding_no');

        PREPARE stmt FROM @sql ;
        EXECUTE stmt ;
        DEALLOCATE PREPARE stmt";

This Query working in adminar but giving error in php.

Is there any way to write query without using prepare statement?

7
  • The mysql_ database extension will not run multiple queries Commented May 30, 2017 at 12:41
  • 2
    Every time you use the mysql_ database extension in new code this happens it is deprecated and has been for years and is gone for ever in PHP7. If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements. Start here Commented May 30, 2017 at 12:42
  • Yes I read that. But what is alternative for that? Or how the query can be modified in better way? Commented May 30, 2017 at 12:46
  • Look up mysqli_multi_query in the manual Commented May 30, 2017 at 12:47
  • I tried with mysqli_multi_query() too but still remain error to mysql_fetch_assoc() Commented May 30, 2017 at 12:53

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.