What is the purpose of using INNER JOIN in PHP when working with multiple tables?
When working with multiple tables in a database, the INNER JOIN clause in PHP is used to combine rows from two or more tables based on a related column between them. This allows you to retrieve data that is spread across multiple tables and display it in a single result set.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Select data from multiple tables using INNER JOIN
$sql = "SELECT users.username, orders.order_id, orders.total_price
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 Price: " . $row["total_price"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What are some common pitfalls when trying to display different colors for specific values in PHP?
- How can server-side validation of MIME types be improved when handling file uploads in PHP to ensure cross-browser compatibility?
- How can a PHP form handle the submission of a checkbox value as either 1 or 0 based on whether it is checked or unchecked?