PHP PHP Web Application - Displaying People and their Colors

Learn how to create a PHP web application that retrieves data from a MySQL database and displays a list of people along with their associated colors.

$pdo = new PDO("mysql:host=localhost;dbname=your_database_name", "your_username", "your_password");

// Query for all the people
$queryPeople = $pdo->query("SELECT * FROM person");

// Fetch all the people and store them in an array
$arrayPeople = [];
while($person = $queryPeople->fetch(PDO::FETCH_ASSOC)) {
    $arrayPeople[$person['ID']] = $person;
}

// Query for all the colours
$queryColours = $pdo->query("SELECT * FROM colour");

// Attach the colours to the corresponding person in the $arrayPeople array
while($colour = $queryColours->fetch(PDO::FETCH_ASSOC)) {
    $arrayPeople[$colour['personID']]['colours'][] = $colour;
}

// Loop through each person
foreach($arrayPeople as $person) {
    // Display the person's name
    echo "<br>" . $person['name'] . "<br>";

    // Loop through every colour
    foreach($person['colours'] as $colour) {
        // Display the colour
        echo $colour['colour'] . "<br>";
    }
}

// src: https://www.zope-europe.org/avoid-mysql-queries-within-loops/