2

I am trying to make my data by passing an exam id... the numbers are my student numbers. The data is stored in my db like this..

enter image description here

Here is my php code

$sql = "SELECT number, question_id, answer FROM `questions_answers` WHERE exam_id=" . $id;

$command = Yii::app()->db->createCommand($sql);
$data = $command ->query();

This is my for each loop, i am writing to csv file.

foreach($data as $result) {
   fwrite($fp, $result['number'] . "," . $result['answer'] . "\r\n");          
}

This is giving me result like this..

enter image description here

I want my result to be like this.. Where 2 is the answer of Q1 giving by number 3100000123, then 3 is answer of Q2, 1 is answer of Q3. Similarly for next student number.. I have tried different things but none of them worked for me. How can i achieve my data like this?

enter image description here

4 Answers4

3

try this.

 SELECT number, SUM( IF( question_id =1, answer, NULL ) ) AS Q1, 
 SUM( IF( question_id =2, answer, NULL ) ) AS Q2,
 SUM( IF( question_id =3, answer, NULL ) ) AS Q3,
 FROM test
 GROUP BY number;
PHP Dev
  • 483
  • 3
  • 16
1

Try this way:

$newArr = array();
foreach($data as $result) {
    $newArr[$result['number']][] = $result['answer'];
}

foreach($newArr as $number=>$answer) {  
    $answer_sring = implode(",",$answer);
    fwrite($fp, $number . ", ".$answer_sring. "\r\n");                  
}
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33
0

You can use GROUP_CONCAT

$sql = "SELECT number, GROUP_CONCAT(question_id) question_id, GROUP_CONCAT(answer) answer FROM `questions_answers` WHERE exam_id=" . $id ." GROUP BY number";
Abdullah Al Shakib
  • 2,034
  • 2
  • 15
  • 16
0

You can make use of PIVOT. Let's say your source table is named tab. Then you make use of the PIVOT in the following way :

SELECT  *
FROM    
(SELECT     question_id,
            answer,
            number
 FROM       tab
) src
PIVOT
(
  MAX(answer)
  FOR question_id IN ([1], [2], [3])
) piv

You would assign this to the $sql variable :

$sql = '
    SELECT  *
    FROM    
    (SELECT     question_id,
                answer,
                number
     FROM       tab
    ) src
    PIVOT
    (
      MAX(answer)
      FOR question_id IN ([1], [2], [3])
    ) piv'

You can see this working here -> http://rextester.com/RJDP17408

Hope this helps!!!

Satwik Nadkarny
  • 5,086
  • 2
  • 23
  • 41