What are the best practices for optimizing PHP code when retrieving and displaying data from a database?

When retrieving and displaying data from a database in PHP, it is important to optimize the code to improve performance. One way to do this is by minimizing the number of database queries and using efficient query techniques like JOINs. Additionally, using prepared statements can help prevent SQL injection attacks and improve overall security.

// Connect to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Retrieve data using a single query with JOIN
$query = "SELECT users.id, users.name, orders.order_date
          FROM users
          INNER JOIN orders ON users.id = orders.user_id
          WHERE users.id = 1";
$result = $connection->query($query);

// Display data
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "User ID: " . $row["id"] . " | Name: " . $row["name"] . " | Order Date: " . $row["order_date"] . "<br>";
    }
} else {
    echo "No results found.";
}

// Close the connection
$connection->close();