'How can I use mysql foreign key in PHP

I have a pictures table and a users table. In my pictures table I have the foreign key of the users to know to which user the picture belongs.

I then list all my photos on a PHP page. I can show the ID of the user who owns the picture since the user ID is in the mysql picture table (foreign key). I do echo $picture["owner_id"]; however, I would like the user's name to be displayed next to the photo and not their ID.

What can I do? I thought about doing a function that iterates over each user and when the ID is equal to the user's ID based on the user's name and then I can do an echo the name but I think there must be a better way

my function du list pictures :

    public function listPictures_session()
{
    $this->open();
    $stmt = $this->pdo->prepare("SELECT * FROM pictures GROUP BY pictures.id ORDER BY pictures.id DESC");
    $stmt->execute();
    return $stmt->fetchAll();
}

what is in my controller :

    public function index()
{
    global $pictures; //Pour voir les photos, on s'adresse au modèle et on créé une variable qu'on appel pictures
    $pictures = $this->model->listPictures_session(); //Et on dit que la variable global pictures c'est le résultat de l'appel d'une fonction 
    require "../app/view/_templates/header.php";
    require "../app/view/home.php";
    require "../app/view/_templates/footer.php";
}

and on my home.php page :

<table>    
<tbody>
            <?php
            global $pictures;
            foreach ($pictures as $picture) { 
            ?>
                <tr>
                    <td>
                        <?php
                        echo $picture["owner_id"];
                        ?>
                    </td>
                    <td>
                        <?php
                        $cuttedpath = substr($picture["path"], 16);
                        ?>
                        <img class="image" src="<?php echo $cuttedpath; ?>">
                    </td>
                    <td>
                        <?php
                        echo $picture["title"];
                        ?>
                    </td>
                    <td>
                        <?php
                        echo $picture["description"];
                        ?>
                    </td>
                    <!-- <td><button onclick="deleteUser('$user[\"login"]')">Ok</button></td> Pq ça fonctionne pas ?  -->
                <?php
            }
                ?>
                </tr>
        </tbody>
</table>

Thanks for your help and have a nice day



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source