944,070 Members | Top Members by Rank

Ad:
  • PHP Discussion Thread
  • Unsolved
  • Views: 853
  • PHP RSS
Nov 8th, 2009
0

How to display query results under headings derived from another field

Expand Post »
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.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Vikk is offline Offline
3 posts
since Oct 2009
Nov 8th, 2009
0
Re: How to display query results under headings derived from another field
Hey.

Try something like:
php Syntax (Toggle Plain Text)
  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.)
Reputation Points: 93
Solved Threads: 70
Posting Pro
Atli is offline Offline
526 posts
since May 2007
Nov 8th, 2009
0
Re: How to display query results under headings derived from another field
Hi Atli,

Thanks for your response.

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

Cheers
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Vikk is offline Offline
3 posts
since Oct 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in PHP Forum Timeline: Creating dynamic links with smarty.
Next Thread in PHP Forum Timeline: Forget Password in PHP





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC