I created a mySQL database with phpMyAdmin in my local server. In this database I store the names and the favourite NBA teams of my friends.This is obviously a many-to-many relationship. For this a reason, I created three tables: one with the id & name of my friends, one with the id & name of the teams and one with friends_id and teams_id (which is the relations table). This is more clearly shown by the following MySQL script:
CREATE TABLE `friends` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `teams` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `relations` (
`friends_id` int(4) NOT NULL AUTO_INCREMENT,
`teams_id` int(4) NOT NULL AUTO_INCREMENT,
)
I want to give an json output with these data and for this reason I run the following PHP script:
<?php
$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);
$sql = 'SELECT * FROM teams;';
$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);
$sql = 'SELECT * FROM relations;';
$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 this does not give a valid json output overall but three distinct json arrays. For example, something like this:
[...,
{
"id": "3",
"name": "David Belton",
},
...]
[...,
{
"id": "4",
"name": "Boston Celtics",
},
...]
[...,
{
"friends_id": "3",
"teams_id": "4"
},
...]
How can I print all of my tables with having a valid json output?