How to display query results under headings derived from another field

Reply

Join Date: Oct 2009
Posts: 3
Reputation: Vikk is an unknown quantity at this point 
Solved Threads: 0
Vikk Vikk is offline Offline
Newbie Poster

How to display query results under headings derived from another field

 
0
  #1
19 Days Ago
Hi all,

Please I'm a newbie in PHP and MySQL, I have results from a GROUP BY (grouped by col2) query in the format.

col1 | col2
-----------
a1 | a
a2 | a
a3 | a
a4 | a
b1 | b
b2 | b
b3 | b


I wish to display the results in the format
----
a
----
a1
a2
a3
a4
----
b
----
b1
b2
b3

I'll appreciate any help on how to go about this.
Reply With Quote Quick reply to this message  
Join Date: May 2007
Posts: 431
Reputation: Atli is on a distinguished road 
Solved Threads: 56
Atli's Avatar
Atli Atli is offline Offline
Posting Pro in Training
 
0
  #2
19 Days Ago
Hey.

Try something like:
  1. <?php
  2. $dbLink = new mysqli('host', 'user', 'pwd', 'db');
  3.  
  4. $result = $dbLink->query("... Put your query here ...");
  5. if($result)
  6. {
  7. $data = array();
  8.  
  9. // Loop through all the returned rows and group the values
  10. // into the $data array based on the 'col2' field.
  11. while($row = $result->fetch_assoc($result)
  12. {
  13. $data[$row['col2']][] = $row['col1'];
  14. }
  15.  
  16. // Loop through the 'col2' values and print a list of
  17. // 'col1' values for each of them.
  18. foreach($data as $_col2 => $_col1_list)
  19. {
  20. echo "----\n{$_col2}\n----\n";
  21. foreach($_col1_list as $_col1)
  22. {
  23. echo $_col1, "\n";
  24. }
  25. }
  26. }
  27. else
  28. {
  29. echo "Your query phailed! " . $dbLink->error;
  30. }
  31. ?>

If you are trying to do this sort of formatting using MySQL alone... don't. MySQL is a database system, meant to store data and return it in a very basic way.
Formatting the data for output is a job for the front-end application. (PHP, in this case.)
Please do not ask for help in a PM. Use the forums.
And use [code] tags!
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 3
Reputation: Vikk is an unknown quantity at this point 
Solved Threads: 0
Vikk Vikk is offline Offline
Newbie Poster
 
0
  #3
19 Days Ago
Hi Atli,

Thanks for your response.

I don't intend to format with MySQL, just used the '----' here for clarity purposes.

Cheers
Reply With Quote Quick reply to this message  
Reply

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC