I am new to PHP and looking for efficient ways to return data from a database. Suppose I have a UserProfile table that has a one-to-many relationship with UserInterest and UserContact:
Select p.Id, p.FirstName, p.LastName, i.Name as Interests, c.Email, c.Phone from UserProfile p left join UserInterest i on p.Id = i.UserProfileId left join UserContact c on p.Id = c.UserProfileId where p.Id = 1
An efficient way to obtain data would be to create a multidimensional array, for example:
$user = array( "FirstName" => "John", "LastName" => "Doe", "Gender" => "Male", "Interests" => array( "Hiking", "Cooking"), "Contact" => array( "Email" => " john.doe@gmail.com ", "Phone" => "(555) 555-5555"));
I can't seem to figure out how this will be built in PHP. For simple data like interests, I could use group_concat (i.Name) as interests in the query to return interests back as a comma-separated list on the same line, however for an associative array like Contact, I would like to have the ability to get a handle to each key in the array using $ user ['Contact'] ['Email'].
From a โbest practiceโ point of view, I would suggest that building such an array in a single query is much better than hitting the database several times to retrieve this data.
Thanks!
Neil
source share