I’m working on a PHP web application where users can create trips to destinations, and invite other users on these trips.
I have MySql tables for Destinations, Trips, and Users, and a table called Invites to resolve the many-to-many relationship between Users and Trips.
For each of these tables, I’ve created a class within my application (so Destinations is a class, Trips is a class, etc.). I’ve written a static function for each of these classes that enables objects to be instantiated and their properties assigned from a MySQL query (so each row returned from a SELECT * query results in an object being instantiated and properties assigned).
I’m trying to create a page where my user can view details of all of the trips they have planned. This page will show the destination (from Destinations), trip details (such as date from Trips) and details of the users they have invited (such as username from Users) and put all of this data in an html table where each trip is a row.
To achieve this, so far I’ve been instantiating Trips which relate to the user’s user_id, Destinations and Invites which relate to those Trips, and Users which relate to those Invites. I’ve then used nested foreach loops to display these as necessary, such as the below:
foreach($trips as $trip) {
foreach($invites as $invite) {
foreach($invited_users as $invited_user) {
if($invite->trip_id == $trip->id && $invite->guest_id == $invited_user->id) {
echo $invited_user->name;
} } } }
Which I can see is horrible and no way to do this.
From reading around, I think I want to use MySQL to join the 4 tables, and then select only data relating to my relevant trips. What I’m not sure of though is:
a) How do I instantiate the objects and assign their properties correctly from this MySQL result?
b) Even with that done, how do I avoid the expensive foreach loops to display the correct data alongside the correct trip?
Is there a “best practice” way of displaying data from multiple related database tables in an object oriented way?
I think you are complicating things, you don’t need to load all the data at once.
Why iterate over all trips, while you need to display the trips of one user ?
A naïve but simple approach with OOP : a
Userclass with a method to retrieve user’s related trips.It could return an array of
Trip, having itself references of invited users :Ideally a
Userinstance would be stored in session