What are best practices for structuring PHP queries when retrieving data from multiple tables with specific criteria?

When retrieving data from multiple tables with specific criteria in PHP, it's best to use JOIN clauses in your SQL query to combine the tables based on their relationships. This allows you to retrieve the necessary data in a single query rather than making multiple separate queries. Additionally, you can use WHERE clauses to filter the results based on specific criteria.

<?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);
}

// Query to retrieve data from multiple tables with specific criteria
$sql = "SELECT * FROM table1 
        JOIN table2 ON table1.id = table2.table1_id 
        WHERE table1.column = 'value' AND table2.column = '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();
?>