How can a JOIN statement be used in PHP to combine data from two tables in a MySQL database?
To combine data from two tables in a MySQL database using a JOIN statement in PHP, you can write a SQL query that specifies the tables to be joined and the columns to be retrieved. This allows you to retrieve data from multiple tables based on a related column between them.
<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to join two tables and retrieve data
$sql = "SELECT table1.column1, table2.column2
FROM table1
JOIN table2 ON table1.id = table2.id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>