How can the code snippet be optimized to improve performance when processing and displaying sorted data from a MySQL database in PHP?

When processing and displaying sorted data from a MySQL database in PHP, one way to optimize performance is to fetch only the necessary data from the database and limit the number of records retrieved. This can be achieved by using the LIMIT clause in the SQL query to fetch only a subset of the data. Additionally, using an index on the column being sorted can also improve performance.

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

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch sorted data with LIMIT clause
$sql = "SELECT * FROM table_name ORDER BY column_name LIMIT 100";
$result = $conn->query($sql);

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

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