I would do the work, in "reverse":
- Fetch all products matching title with matching user id and
firstname.
- Sort results by user in PHP
Sometimes it's faster to do things what way rather than trying to ask too much to MySQL.
MySQL is faster on simple query and PHP is good to sort datas as long as your logic is right.
Here is an exemple:
1 - Fetch data (MySQL):
SELECT p.*, u.id AS user_id, u.firstname AS user_firstname
FROM `products` AS p
INNER JOIN `user` AS u ON u.id = p.user_id
WHERE p.make LIKE '%Porsche%'
ORDER BY p.make, u.id
I don't know the full list of columns in you products table but it should produce something like this for each row:
id, make, user_id, user_firstname
2 - Sort results with PHP (assuming you use PDO, which I strongly recommand):
// Data will contain the sorted results
$data = array();
// This variable will be used to be sure results owning by a certain user are children of this user
$curent_index = null;
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
// Assign index to row user id (if different from current)
if($current_index != $row['user_id']) {
$current_index = $row['user_ic'];
}
// Create entry matching the user (if doesn't exist)
if(!array_key_exists($current_index, $data)) {
$data[$current_index] = array(
'firstname' => $row['firstname'],
'products' => array()
);
}
// Add product in data user array
$data[$current_id]['products'][$row['id']] = array(
'make' => $row['make'],
// whatever other fields product have
);
}
This should produce a result array like so :
1 => array(
'firstname' => 'Toto',
'products' => array(
1 => array(
'make' => 'My Porsche'
),
2 => array(
'make' => 'Porsche, an history of red cars'
),
//...
)
),
3 => array(
'firstname' => 'Titi',
'products' => array(
7 => array(
'make' => 'Porsche or Ferrari?'
),
10 => array(
'make' => 'Why Porsches are so expensive?'
),
// ...
)
)
products. how is the database designed.