Henry Aspden
Henry Aspden

Reputation: 1945

Php mySQL loop within loop from 2 tables

So, I have 2 tables and I want to try and do an iterative loop within a loop...

Table one is a list of Football Games Table 2 is a list of The channels these are on.

Table 1 has an auto increment ID for each game & then table two has a column which relates to this...

Heres an example of table 1

	
id | title                 | highlight |  date       |  time	 	|	logo	|	background
1  | Sevilla vs Celta Vigo | No        |  2017-04-28 |  18:00:00	|	La Liga	|	"background": "url"

and here of table 2

	
id | name
1  | Sports Pick 2
1  | Sports Pick 2 HD
1  | Sports Pick UHD

Now what I am wanting to do is display a loop of table 1, however for each value, also loop the channels where the ID matches in table 2

This is the code I have written so far

<?php

	echo "<pre>{
	\"fixtures\": [<pre>";


    //connect to mysql db
    $con = mysql_connect("localhost","DATABASEUSERHERE","DATABASEPASSWORDHERE") or die('Could not connect: ' . mysql_error());
    //connect to the employee database
    mysql_select_db("DATABASENAMEHERE", $con);

	$sql = "SELECT * FROM fixture_list";
	$result = mysql_query($sql);

	while ($row = mysql_fetch_array($result)) {
	    echo '{
			"title": "'.$row[title].'",
			"highlight": "'.$row[highlight].'",
			"date": "'.$row[date].'",
			"time": "'.$row[time].'",
			"logo": "'.$row[logo].'",'.$row[background].'
			';
		echo '"channels": [
				{ "name": "Sports Pick 2" },
				{ "name": "Sky Sports 2" }
			]
		},';
	}
	
	echo "
	]
}";


?>

so this works well, but i've only got the 1st loop running here and am struggling to see how or where I'd pop the second loop and how i'd do a foreach or something like that to get the relevant values in the second loop...

Here is a copy of the desired output I am looking for

{
	"fixtures": [
{
			"title": "Sevilla vs Celta Vigo",
			"highlight": "No",
			"date": "2017-04-28",
			"time": "18:00:00",
			"logo": "La Liga",
			"background": "URL",
			"channels": [
				{ "name": "Sports Pick 2" },
				{ "name": "Sports Pick 2 HD" },
				{ "name": "Sports Pick UHD" }
			]
		},
	]
}

I'm looking forward to some guidance on this and seeing how this works out... thanks in anticipation !

Upvotes: 0

Views: 774

Answers (2)

Junius L
Junius L

Reputation: 16122

Use mysqli as msql has been deprecated

<?php

echo "<pre>{
    \"fixtures\": [<pre>";


//connect to mysql db
$con = mysqli_connect("localhost","root","000000");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    die();
}
//connect to the employee database
mysqli_select_db($con, 'ng_app');

$sql = "SELECT * FROM fixture_list";
$result = mysqli_query($con, $sql);
$json = '';
while ($row = mysqli_fetch_array($result)) {
    $json .= '{
            "title": "'.$row['title'].'",
            "highlight": "'.$row['highlight'].'",
            "date": "'.$row['date'].'",
            "time": "'.$row['time'].'",
            "logo": "'.$row['logo'].'",
            "background" : "' . $row['background'] . '",
            ';
    $json .= '"channels": [
                ' . getChannels($row['id'], $con) . '
            ]
        },';
}
echo rtrim($json, ',');
echo "
    ]
}";


function getChannels($fixture_id, $con) {
    $sql = "SELECT * FROM `channels` WHERE `id` = $fixture_id";
    $result = mysqli_query($con, $sql);
    $data = '';
    while ($row = mysqli_fetch_array($result)) {
        $data .= '{"name": "' . $row['name'] .'"},';
    }
    return rtrim($data, ',');
}

?>

Output

{
"fixtures": [{
  "title": "Sevilla vs Celta Vigo",
  "highlight": "No",
  "date": "2017-04-28 00:00:00",
  "time": "18:00:00",
  "logo": "La Liga",
  "background": "URL",
  "channels": [{
    "name": "Sports Pick 2"
  }, {
    "name": "Sports Pick 2 HD"
  }, {
    "name": "Sports Pick UHD"
   }]
 }]
}

Upvotes: 1

Paul Spiegel
Paul Spiegel

Reputation: 31772

I would select both tables in two queries and do the assignments in PHP.

Since I don't know the mysql_* functions - Here is a mysqli solution:

$con = new mysqli('localhost', 'DATABASEUSERHERE', 'DATABASEPASSWORDHERE', 'DATABASENAMEHERE');

$data = [];
$result = $con->query("SELECT * FROM fixture_list");
while($row = $result->fetch_assoc()) {
    $id = $row['id'];
    unset($row['id']);
    $row['channels'] = [];
    $data[$id] = $row;
}

$result = $con->query("SELECT * FROM channels");
while($row = $result->fetch_assoc()) {
    $data[$row['id']]['channels'][] = ['name' => $row['name']];
}

You can now loop throug the $data array and print the values. Or just use json_encode:

echo json_encode($data);

Or

echo json_encode($data, JSON_PRETTY_PRINT);

Upvotes: 1

Related Questions