Hi! Could we please enable some services and cookies to improve your experience and our website?

PHPize Online / SQLize Online  /  SQLtest Online

A A A
Login    Share code      Blog   FAQ

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

Copy Format Clear
CREATE TABLE Gamelog ( id INTEGER PRIMARY KEY, game_number INTEGER, home_team_id INTEGER, away_team_id INTEGER ); CREATE TABLE Teams ( id INTEGER PRIMARY KEY, name TEXT ); CREATE TABLE Goals ( id INTEGER PRIMARY KEY, game_number_id INTEGER, team_id_goal INTEGER ); INSERT INTO Gamelog (id, game_number, home_team_id, away_team_id) VALUES (1, 1, 1, 2), (2, 2, 3, 4); INSERT INTO Teams (id, name) VALUES (1, 'MTL'), (2, 'BOS'), (3, 'CGY'), (4, 'EDM'); INSERT INTO Goals (id, game_number_id, team_id_goal) VALUES (1, 1, 2), (2, 1, 2), (3, 1, 1), (4, 2, 4), (5, 2, 4);

Stuck with a problem? Got Error? Ask AI support!

Copy Clear
Copy Format Clear
<?php // Using PDO $sql = "SELECT g.game_number, ht.name AS home_team, at.name AS away_team FROM Gamelog g JOIN Teams ht ON g.home_team_id = ht.id JOIN Teams at ON g.away_team_id = at.id"; $stmt = $pdo->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(); foreach ($result as $row) { echo "game " . $row["game_number"] . ": " . $row["home_team"] . " vs " . $row["away_team"] . "\n"; $sql2 = "SELECT t.name AS team_name FROM Goals g JOIN Teams t ON g.team_id_goal = t.id WHERE g.game_number_id = :game_number"; $stmt2 = $pdo->prepare($sql2); $stmt2->execute(['game_number' => $row["game_number"]]); $result2 = $stmt2->fetchAll(); foreach ($result2 as $row2) { echo "goals in game " . $row["game_number"] . ": " . $row2["team_name"] . " scores\n"; } }
Copy Clear