How can a PHP developer use JOIN statements to link tables in a SQL query for filtering results based on specific criteria?
To link tables in a SQL query using JOIN statements for filtering results based on specific criteria, a PHP developer can specify the tables to be joined and the criteria for joining them in the query. This allows the developer to retrieve data from multiple tables based on related columns, enabling more complex filtering and data retrieval operations.
<?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 JOIN statement to link tables and filter results
$sql = "SELECT table1.column1, table2.column2
FROM table1
INNER JOIN table2 ON table1.id = table2.id
WHERE table1.criteria = 'value' AND table2.criteria = 'value'";
$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();
?>