I created a mySQL database with phpMyAdmin in my local server. In this database I stored the names and the favourite NBA teams of my friends (along with an id as a primary key for the database). However, some of my friends may have two favourite teams. I wrote and run the following php script to retrieve these data from the one table I have in the database (I know that it is not the best way to have one table for many-to-many relationship) and project them on my local web server (XAMPP):
$dbServername = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'Friends';
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
header('Content-Type: application/json');
$sql = 'SELECT * FROM friends;';
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
arr = [];
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
}
echo json_encode($arr, JSON_PRETTY_PRINT);
However, in this way I take this output for one person:
[{
"id": "1",
"name": "David Belton",
"team": "Boston Celtics"
}, {
"id": "1",
"name": "David Belton",
"team": "Cleveland Cavaliers"
}]
However, I would like to get this something like this as output for each specific person:
{
"id": "1",
"name": "David Belton",
"team": ["Boston Celtics", "Cleveland Cavaliers"]
}
Is this possible in PHP?
If so, is it recommended or should I do this with MySQL back at the database?