简体   繁体   中英

PHP MySQL: How to retrieve all images associated to an item id from images table

So I have two tables.

Items table:

+---------+-----------+
| item_id | item_name |
+---------+-----------+
|       1 | Item One  |
|       2 | Item Two  |
+---------+-----------+

Images table:

+---------+----------------------+
| item_id |      item_image      |
+---------+----------------------+
|       1 | clofr9ohuvex5cxeyrfm |
|       1 | slnorjbqfd2x7ks0marp |
|       1 | oomkjtomvasklx9be4sq |
|       2 | um8donrpeuvfrmqb7qt  |
|       2 | lowcvoaijxniiqdj5eoe |
|       2 | qwxfartcsdyusw4lrngi |
+---------+----------------------+

My php code to get list of items with their associative images:

$itemsQuery = $db->prepare("
        SELECT *
        FROM items a,item_images b
        WHERE a.item_id = b.item_id
    ");
    $itemsQuery->execute();
    $items = $itemsQuery->fetchAll(PDO::FETCH_ASSOC);

    var_dump($items);

I am getting 6 results instead of 2.

What I want is to show the 2 items present in the "items table" with their associative images from the "images table" based on the item_id.

I can query the "items table" and loop through it to query the database one more time to get the images. But how can I do it in one database call?

You can use GROUP_CONCAT to get MySQL to group all the values from the second table to a single column for you:

SELECT 
    a.*, GROUP_CONCAT(b.item_image) AS item_images
FROM
    items a,item_images b
WHERE
    a.item_id = b.item_id
GROUP BY
    a.item_id

The result will be a key named item_images that contain each item_image for that item , separated by , :

um8donrpeuvfrmqb7qt,lowcvoaijxniiqdj5eoe,qwxfartcsdyusw4lrngi

You can then use explode on the PHP side if you want it as an array instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM