How can PHP code be optimized to efficiently handle the output and formatting of data retrieved from a MySQL database for display on a webpage?

To optimize PHP code for efficiently handling data retrieved from a MySQL database for display on a webpage, you can use techniques like fetching only the necessary data, using prepared statements to prevent SQL injection, caching query results, and minimizing loops and conditional statements for formatting.

// Example PHP code snippet for optimizing data retrieval and display from MySQL database

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

// Fetch data from database
$result = $mysqli->query("SELECT * FROM table");

// Check if data exists
if ($result->num_rows > 0) {
    // Loop through data and display on webpage
    while ($row = $result->fetch_assoc()) {
        echo "<p>" . $row['column1'] . " - " . $row['column2'] . "</p>";
    }
} else {
    echo "No data found.";
}

// Close database connection
$mysqli->close();