What are the best practices for optimizing PHP scripts that involve sorting and displaying data from a database based on specific criteria?

When optimizing PHP scripts that involve sorting and displaying data from a database based on specific criteria, it is important to utilize SQL queries efficiently, minimize database calls, and implement proper indexing on the database tables. Additionally, caching results and using pagination can help improve performance and reduce load times.

// Example PHP code snippet for optimizing sorting and displaying data from a database

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

// Query to fetch data from the database based on specific criteria
$query = "SELECT * FROM table_name WHERE criteria = 'value' ORDER BY column_name LIMIT 10";
$result = $connection->query($query);

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

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