What best practices should PHP developers follow when writing SQL queries to join tables and fetch specific data?

When writing SQL queries to join tables and fetch specific data in PHP, developers should follow best practices such as using parameterized queries to prevent SQL injection attacks, properly escaping user input, and optimizing queries for performance by selecting only the necessary columns and using appropriate indexing.

<?php
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a parameterized SQL query with joins
$stmt = $pdo->prepare("SELECT users.username, orders.order_date 
                      FROM users 
                      INNER JOIN orders ON users.id = orders.user_id 
                      WHERE users.id = :user_id");

// Bind the user_id parameter
$user_id = 1;
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Output the data
foreach ($results as $row) {
    echo $row['username'] . " made an order on " . $row['order_date'] . "<br>";
}
?>