How can SQL joins be utilized to optimize the retrieval of data from multiple tables in PHP?
When retrieving data from multiple tables in a database using PHP, SQL joins can be utilized to optimize the process by combining related data from different tables into a single result set. By using SQL joins, you can avoid making multiple queries and fetching data separately, which can improve performance and reduce the number of database calls.
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query with INNER JOIN to retrieve data from multiple tables
$sql = "SELECT users.username, orders.order_id, orders.total_amount
FROM users
INNER JOIN orders ON users.user_id = orders.user_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"]. " - Order ID: " . $row["order_id"]. " - Total Amount: " . $row["total_amount"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>