-4

I have searched for the references for this question. however, found row based solutions. Can you please provide any references for column based... mysql database contains three coulmns

question | Answer | IP
   q1    | a3     | 0.0.0.0
   q2    | a2     | 0.0.0.0  
   q3    | a4     | 0.0.0.0
   q1    | a3     | 1.1.1.1
   q2    | a2     | 1.1.1.1  
   q3    | a2     | 1.1.1.1

The output for this in php table like....

question | IP       | IP      | and so on....
         |  0.0.0.0 | 1.1.1.1 |
   q1    | a3       | a3      |
   q2    | a2       | a2      | 
   q3    | a4       | a2      |

Thanks, ShailShin

ShailShin
  • 69
  • 3
  • 5
    I have NO idea what you want to achieve as your result. Elaborate the question. – Basit Aug 20 '14 at 05:44
  • Databases work in rows. The only way you can get the data in columns is to use a union. However, please elaborate your question more. – ZeroBased_IX Aug 20 '14 at 06:09
  • possible duplicate of [MySQL pivot table](http://stackoverflow.com/questions/7674786/mysql-pivot-table) – Peter O. Aug 20 '14 at 06:58

1 Answers1

0

assuming you have a mysql table setup like this

https://www.dropbox.com/s/cth0mkfwt382z0g/Screenshot%202014-08-20%2016.27.48.png

and you have your php files setup to db properly

  //query database for data
  $result = mysql_query("SELECT question, answer, ip FROM test_answers");

  //Create some arrays
  $answer_array = array();
  $ip_array = array();
  $question_array = array();

  //loop through the mysql data and populate the arrays
  while ($row = mysql_fetch_object($result)) {
    $answer_array[$row->ip][$row->question] = $row->answer;
    $ip_array[] = $row->ip;
    $question_array[] = $row->question;
  }

  //remove dups
  $ip_array = array_unique($ip_array);
  $question_array = array_unique($question_array);

  //print out the view
  echo "<table>";
  //heading row
  echo "<tr><td>question</td>";
  foreach($ip_array as $ip) {
    echo "<td>$ip</td>";
  }
  echo "</tr>";
  //answer rows
  foreach($question_array as $question) {
    echo "<tr><td>$question</td>";
      foreach($ip_array as $ip) {
         echo "<td>" . $answer_array[$ip][$question] . "</td>";
      }
    echo "</tr>";
  }
  echo "</table>";

then you'll end up with this

https://www.dropbox.com/s/yhuy5br3p1o3npg/Screenshot%202014-08-20%2016.31.06.png

James
  • 774
  • 6
  • 8