How can you effectively use a JOIN statement in PHP MySQL queries to retrieve data from multiple tables?
When you need to retrieve data from multiple tables in a MySQL database, you can use a JOIN statement in your PHP MySQL query. By specifying the tables you want to join and the columns to match on, you can combine data from different tables into a single result set. This allows you to retrieve related data in a single query rather than making multiple queries.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query with JOIN statement
$sql = "SELECT orders.order_id, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Order ID: " . $row["order_id"]. " - Customer Name: " . $row["customer_name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>