How can a JOIN statement be used to combine data from multiple tables in PHP?
To combine data from multiple tables in PHP using a JOIN statement, you can specify the tables you want to join and the columns you want to retrieve data from in the SQL query. By using different types of JOINs such as INNER JOIN, LEFT JOIN, or RIGHT JOIN, you can control how the data is combined based on the relationship between the tables.
<?php
// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");
// SQL query to join two tables based on a common column
$query = "SELECT table1.column1, table2.column2
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column";
// Execute the query
$result = $connection->query($query);
// Fetch and display the results
while ($row = $result->fetch_assoc()) {
echo $row['column1'] . " - " . $row['column2'] . "<br>";
}
// Close the connection
$connection->close();
?>
Keywords
Related Questions
- What best practices should be followed when constructing SQL queries in PHP to avoid syntax errors and improve readability?
- In the context of PHP development, what are some common reasons for errors to occur after making changes to code or integrating new features like mods?
- How can you ensure that only one image is returned per HTTP request when displaying images from a folder in PHP?