How can PHP developers effectively query and retrieve data from multiple tables within a single database using PHP and MySQLi?
To effectively query and retrieve data from multiple tables within a single database using PHP and MySQLi, developers can use SQL JOIN statements to combine data from different tables based on a related column. By specifying the columns to select and the tables to join in the SQL query, developers can fetch data from multiple tables in a single query.
<?php
// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// SQL query to retrieve data from multiple tables using JOIN
$sql = "SELECT table1.column1, table2.column2
FROM table1
JOIN table2 ON table1.common_column = table2.common_column";
// Execute the query and fetch the results
$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"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$connection->close();
?>