How can PHP developers effectively use WHERE clauses in SQL queries to retrieve specific data from multiple tables?
When using WHERE clauses in SQL queries to retrieve specific data from multiple tables in PHP, developers can use JOIN statements to connect the tables based on a common column. By specifying the table names and column names in the WHERE clause with appropriate conditions, developers can filter the data they want to retrieve accurately.
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query with WHERE clause to retrieve specific data from multiple tables
$sql = "SELECT column1, column2
FROM table1
JOIN table2 ON table1.common_column = table2.common_column
WHERE condition";
$result = $conn->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";
}
$conn->close();
?>