How can SQL joins be utilized in PHP to improve query efficiency and readability?
SQL joins can be utilized in PHP to improve query efficiency and readability by combining data from multiple tables based on a related column between them. This reduces the need for multiple separate queries and allows for more complex data retrieval in a single query.
<?php
// Establish a database connection
$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 with INNER JOIN
$sql = "SELECT users.username, orders.product FROM users
INNER JOIN orders ON users.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"]. " - Product: " . $row["product"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>