title: Convert columns to rows dynamically with records in Mysql - PHP
body: <p>I have this in my database:</p>
  <pre><code> Stud_id        subject      Total
   Abc12          Eng           60
   Abc13          Eng           40    
   Abc12          Math          70
   Abc13          Math          50
  </code></pre>
  <p>This is the output i expect:</p>
  <pre><code> Stud_id        Eng       Math
  
   Abc12          60        70
   Abc13          40        50
  </code></pre>
  <p>If there was a large amount of records, how could i do this in bulk amount? performance and reliability is much needed!</p>
  <p>I tried the following code:</p>
  <pre><code>&lt;?php
  
              ...
              $sql = &quot;select   
                GROUP_CONCAT(DISTINCT
                   CONCAT(
                    'ifnull(SUM(case when sub_code = ''',
                    sub_code,
                    ''' then total end),0) AS `',
                    sub_code, '`'
                  )
                  ) INTO @sql
                  FROM scores_tbl;
              
             (stud_id) as USERID
             , sum(total) as Total,
             ('') as '%'
         
             FROM scores_tbl where class_name='JSS1' AND GROUP by stud_id&quot;;
              $result = $db-&gt;multi_query($sql);
  
              if ($err=mysqli_error($db)) { echo $err.&quot;&lt;br&gt;&lt;hr&gt;&quot;; }
  
              if ($result) {
                do {
                if ($res = $db-&gt;store_result()) {
                    echo &quot;&lt;table width=100% border=1&gt;&lt;tr&gt;&quot;;
      
                // printing table headers
                    for($i=0; $i&lt;mysqli_num_fields($res); $i++)
                    {
                        $field = mysqli_fetch_field($res);
                    echo &quot;&lt;td bgcolor=lightgray&gt;&lt;b&gt;{$field-&gt;name}&lt;/b&gt;&lt;/td&gt;&quot;;
                    }
                    echo &quot;&lt;/tr&gt;\n&quot;;
      
                    // printing table rows
                    while($row = $res-&gt;fetch_row())
                    {
                        echo &quot;&lt;tr&gt;&quot;;
                        foreach($row as $cell) {
                              if ($cell === NULL) { $cell = '(null)'; }
                          echo &quot;&lt;td&gt;$cell&lt;/td&gt;&quot;;
                        }
                        echo &quot;&lt;/tr&gt;\n&quot;;
                    }
                    $res-&gt;free();
                    echo &quot;&lt;/table&gt;&quot;;
          
                  }
                } while ($db-&gt;more_results() &amp;&amp; $db-&gt;next_result());
              }
              $db-&gt;close();
              ?&gt;
  </code></pre>
  <p>It doesn't give any errors, but doesn't work either</p>