I think it's rather a matter of design. I would prefer to keep the code as simple as possible: do sorting at database level, and keep the (business) logic as simple as possible.
Assume that your tables are defined some what like this -
| house_id | kitchen_id | bathroom_id |
| 1 | 101 | 103 |
| 2 | 102 | 104 |
| image_id | image_name | date_entered |
| 101 | image01.jpg | 2004/01/02-11:30 |
| 102 | image02.jpg | 2004/01/02-13:30 |
| 103 | image03.jpg | 2004/01/03-12:30 |
| 104 | image04.jpg | 2004/01/05-13:30 |
Then I would introduce a hash table of SQL statements in the code, indexed by the alias of sorting order. The following code is not tested, just an idea on how this problem may be tackled.
my %SQL = (
order_by_date => 'select image_name from image
where house_id in (
select kitchen_id, bathroom_id
from house where house_id=?
)
order by image_date',
kitchen_first => 'select image_name from image
where image_id =
( select kitchen_id, bathroom_id
from house where house_id = ? )',
bathroom_first => 'select image_name from image
where image_id =
( select bathroom_id, kitchen_id
from house where house_id = ? )',
);
....
$sth = $dbh->prepare( $SQL{order_by_date} );
....
$sth = $dbh->prepare( $SQL{kitchen_first} );
....