473,811 Members | 2,879 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sorting query results into groups

Hey,

I have a 'staff' table with a column 'status', corresponding to a
'statuses' table with the appropriate titles (eg 1 | Editor in Chief).
I want to display on the page the headings (the titles from statuses)
along with all of the staff members with that status ID.

I've attempted this using a query for each possible status, which I
figure was pretty inefficient (plus it didn't work properly). The best
I could do manually was to just display a list of staff and their
statuses sorted in order of the title ranks.

How can I do this efficiently?

-Matt

Sep 6 '05 #1
8 1908
gu************@ gmail.com wrote:
I have a 'staff' table with a column 'status', corresponding to a
'statuses' table with the appropriate titles (eg 1 | Editor in Chief).
I want to display on the page the headings (the titles from statuses)
along with all of the staff members with that status ID.

I've attempted this using a query for each possible status, which I
figure was pretty inefficient (plus it didn't work properly). The best
I could do manually was to just display a list of staff and their
statuses sorted in order of the title ranks.

How can I do this efficiently?


How about (skipping the fetch from the db, assuming you have a result
already):

while ($row =& $res->fetchRow()) {
$staff[$row['title']][] = $row['name'];
}
This should create something like this:

array ( "Secretary" => array (0 => "Lolli Pop",
1 => "Jonsey Jones"
3 => "Bob Bored"),
"Editor in Chief" => array (0 => "Big Fish",
1 => "Jack Sardine"),
...);

Well, you catch the drift.

/Marcin
Sep 6 '05 #2
I have a 'staff' table with a column 'status', corresponding to a
'statuses' table with the appropriate titles (eg 1 | Editor in Chief).
I want to display on the page the headings (the titles from statuses)
along with all of the staff members with that status ID.


You need a query that joins the two tables together. You haven't shown
the table definitions but it would look something like this:

SELECT staff.name, statuses.title
FROM staff, statuses
WHERE staff.statusid = statuses.status id
ORDER BY statuses.rank

---
Steve

Sep 6 '05 #3
Sorry, I should have specified: I already have a join (inner) that does
that. My problem is actually displaying the data in groups.

Marcin: Could you explain a little of what's going on there? I'm pretty
new to all of this. Thanks!

Sep 6 '05 #4
gu************@ gmail.com wrote:
Sorry, I should have specified: I already have a join (inner) that does
that. My problem is actually displaying the data in groups.

Marcin: Could you explain a little of what's going on there? I'm pretty
new to all of this. Thanks!


Jeps... you are creating a two dimentional hash. So, whereas in a
one-dimentional hash you would have:

array (hash => value,
hash2 => value2,
...);

you now have:

array (hash => array (hash => value,
hash2 => value2...),
haash => array (hash3 => value3
...

The foo[] construct is a shorthand for pushing onto an array (similar
to array_push()), but without the ill side-effect of renumbering indexes
(if that's important).

So, basically what I suggested is that when you process your joined
query result, you create a hash with key values equal to the 'status',
and the value an array of names in that status. You can then "foreach"
on that, to parse it out into some table, for instance like this (see
HTML_Table on the table genrating stuff):

<?php
require_once ('HTML/Table.php');
$staff = array ('Editors in Chief' =>
array (array('John', 'Doe'),
array('Bob', 'Edams'), array('Iggy', 'Pop')),
'Copywriters' =>
array(array('Jo e', 'Little'), array('Billy', 'Jean'),
array('Xena', 'Warrior')));

$t = new HTML_Table(arra y('border' => 1));
foreach($staff as $status => $folks) {
$t->addRow(array($ status),
array('colspan' => 2),
'TH');
foreach ($folks as $name) {
$t->addRow($name );
}
}
$t->display();
?>

This will create the following HTML:
<table border="1">
<tr>
<th colspan="2">Edi tors in Chief</th>
<!-- span -->
</tr>
<tr>
<td>John</td>
<td>Doe</td>

</tr>
<tr>
<td>Bob</td>
<td>Edams</td>
</tr>
<tr>
<td>Iggy</td>

<td>Pop</td>
</tr>
<tr>
<th colspan="2">Cop ywriters</th>
<!-- span -->
</tr>
<tr>
<td>Joe</td>

<td>Little</td>
</tr>
<tr>
<td>Billy</td>
<td>Jean</td>
</tr>
<tr>

<td>Xena</td>
<td>Warrior</td>
</tr>
</table>

The benefit here was that you only need to perform one query on the DB
(to fetch the names/status), and you don't really need to sort it by the
"status" field because that will be done during the construction of the
hash.

/Marcin
Sep 6 '05 #5
NC
guitarroman...@ gmail.com wrote:

I have a 'staff' table with a column 'status', corresponding to a
'statuses' table with the appropriate titles (eg 1 | Editor in Chief).
I want to display on the page the headings (the titles from statuses)
along with all of the staff members with that status ID. .... How can I do this efficiently?


Something like this should work (since I don't know your field
naming scheme, I had to invent my own field names):

$query = <<<EOQ
SELECT
staff.firstname AS firstname,
staff.lastname AS lastname,
staff.status AS status,
statuses.title AS title
FROM staff LEFT JOIN statuses ON staff.status = statuses.id
ORDER BY status
EOQ;
$result = mysql_query($qu ery)
or die('Could not execute query: ' . mysql_error());
$status = null;
while ($record = mysql_fetch_arr ay($result, MYSQL_ASSOC)) {
if ($record['status'] <> $status) {
$title = $record['title'];
echo "<p>Status: $title</p>\r\n";
$status = $record['status'];
}
$name = $record['firstname'] . ' ' . $record['lastname'];
echo "<p style='padding-right:10px'>$na me</p>\r\n";
}

Cheers,
NC

Sep 6 '05 #6
NC,

That worked beautifully, thank you a ton!

Sep 7 '05 #7

gu************@ gmail.com a écrit :
NC,

That worked beautifully, thank you a ton!


I'm really interested i have something a bit similar to deal with
(exept i'm a total beginner)
Could you send me a 'create table' instruction that i shall use ?

Sep 8 '05 #8
hey,

Mine is pretty specific to my site, but here's what I'm using:

CREATE TABLE `staff` (
`Staff_id` int(11) NOT NULL auto_increment,
`username` text NOT NULL,
`Staff_Email` text NOT NULL,
`password` text NOT NULL,
`status` text NOT NULL,
`profile` text NOT NULL,
PRIMARY KEY (`Staff_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT= 75 ;

Password is stored as md5. Status is a number corresponding to the
'statuses' table (contains two columns, 'id' and 'title'). Profile is
just html code for that staff member's personal info.

Sep 9 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
5617
by: Guy Erez | last post by:
Hi, I'm running queries with MySql 4.0.17 that return thousands of records. Because I need to present them in GUI, I returieve the results in chunks using LIMIT, for example - get first 100, then the range 100-2000 and so on. The problem is as follows: in the first chunk, MySQL uses one strategy to fetch the results, and in the following chunks - a different strategy.
6
17164
by: Brian | last post by:
Hello, Basically, I'm running a query on a form's activation, and I'd like to have the results of the query be placed into other fields on the same form automatically. Does anybody know how this can be done? I've tried setting the default value of the text fields on the form to be equal to ! using Access' expression
0
1908
by: Rob | last post by:
I doubt this is the best way to do it, but what I came up with was to hide the XML in an HTML Comment then edit the file deleting the HTML stuff and keep the XML results. If anyone has a better solution, I would be interested. Thank you. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim cmd As System.Data.SqlClient.SqlCommand cmd = New System.Data.SqlClient.SqlCommand
9
3067
by: Kelii | last post by:
I've been trying to get this piece to work for a few hours, but have given up. I hope someone out there can help, I think the issue is relatively straightforward, but being a novice, I'm stumped. Below you will find the code I've written and the error that results. I'm hoping that someone can give me some direction as to what syntax or parameter is missing from the code that is expected by VBA. Overview: I'm trying to copy calculated...
6
2592
by: tom_b | last post by:
Hi, I'm using Mysql and PHP,I have a simple table in my DB, looks something like this: id jim bob bill 1 20 30 15 2 20 35 15 etc, what i need to do is get the sums for each column (I can do that), then output each field_name with the corresponding sum sorted desc like this
2
3440
by: Himmel | last post by:
Hello! The reference database I currently use runs queries that pull data from hundreds of tables in order to create user-friendly form view. The problem is that these queries can take upwards of 30 seconds to return. The solution that I've devised is to create an admin function to cache all these query results and then dump that data into a new, consolidated table, and then have the users search through those new tables. Since our...
1
2844
by: igor221189 | last post by:
Hello everyone. I have Access 2000 database which holds student records in the school.It stores subject grades for each student.In the 'Student Grade Form', I would like to search student surname using a query rather than scrolling down through 100s of names.Also, I would like the results of the query search to show in the form automatically in fields of 'Student name' and 'Student surname' based on the results.Is there any way I can do...
1
1625
by: mcfly1204 | last post by:
I am generating an XML document using C#, and I have a question on how to populate the value of a particular object with the corresponding value from a SQL query. For example, if I have a query such as: select col1,col2,col3 from table where id=@id I then want to take those results, and insert them into the appropriate node of the XML document I am generating. textWriter.WriteStartElement("Column 1"); textWriter.WriteString(col1...
1
1974
by: Dave Mallett | last post by:
very new to Access. Trying to export query results via macro and transfertext, but keep getting error message stating "Microsoft Jet Engine cannot find the object 'HRQ-DM_Prd1_qtr.txt'. Make sure the object exists and that you spell its name and path correctly". I don't understand why it's saying that it can't find the 'object'...I'm exporting, not importing. I tried changing the file names/query names and shortening paths, etc., but still...
0
9722
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10393
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6882
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4334
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.