How can the PHP code be optimized to improve performance when fetching and displaying data from multiple tables in MySQL?

When fetching and displaying data from multiple tables in MySQL using PHP, one way to optimize performance is to use JOIN queries instead of making multiple separate queries. By using JOINs, you can retrieve all the necessary data in a single query, reducing the number of round trips to the database and improving efficiency.

<?php
// Connect to MySQL database
$conn = new mysqli("localhost", "username", "password", "database");

// Query to fetch data from multiple tables using JOIN
$sql = "SELECT t1.column1, t2.column2 FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data from query result
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close database connection
$conn->close();
?>