How can relationships between different tables be established in PHP when querying data?
When querying data in PHP, relationships between different tables can be established by using SQL JOIN statements. By using JOINs, you can combine data from multiple tables based on a related column, allowing you to retrieve data from different tables in a single query.
<?php
// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");
// Query to select data from two tables using a JOIN statement
$query = "SELECT table1.column1, table2.column2 FROM table1 INNER JOIN table2 ON table1.id = table2.table1_id";
// 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();
?>