How can the JOIN command in MySQL be effectively used to retrieve and display data from multiple related tables in a PHP application?
When retrieving data from multiple related tables in a MySQL database in a PHP application, the JOIN command can be used to combine rows from two or more tables based on a related column between them. This allows for the retrieval of data from multiple tables in a single query, simplifying the process and improving performance.
<?php
// Establish a connection to the MySQL database
$connection = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Query to retrieve data from multiple related tables using JOIN
$sql = "SELECT column1, column2, column3
FROM table1
JOIN table2 ON table1.id = table2.table1_id";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. " - Column3: " . $row["column3"]. "<br>";
}
} else {
echo "0 results";
}
$connection->close();
?>
Keywords
Related Questions
- Are there specific headers that should be included when sending HTML emails to avoid being marked as spam by email providers?
- How can you ensure that complete data records are deleted from a database table in PHP?
- How can PHP be utilized to properly normalize database structures and avoid creating excessive tables?