What are best practices for optimizing SQL queries in PHP to prevent issues with fetching data from multiple tables?

To optimize SQL queries in PHP and prevent issues with fetching data from multiple tables, it is important to use proper indexing, limit the number of columns retrieved, avoid using SELECT * when possible, and use JOINs instead of multiple queries.

<?php
// Example of optimizing SQL query using JOIN
$query = "SELECT users.name, orders.order_date
          FROM users
          JOIN orders ON users.id = orders.user_id
          WHERE users.id = 1";

$result = mysqli_query($connection, $query);

// Fetch data from the result set
while ($row = mysqli_fetch_assoc($result)) {
    echo "User: " . $row['name'] . " - Order Date: " . $row['order_date'] . "<br>";
}

// Free result set
mysqli_free_result($result);

// Close connection
mysqli_close($connection);
?>