How can PHP be used to efficiently sort and display data from a MySQL database?

To efficiently sort and display data from a MySQL database using PHP, you can use SQL queries to retrieve the data in the desired order and then use PHP to loop through the results and display them on the webpage.

<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Query to select data from database and sort by a specific column
$sql = "SELECT * FROM table_name ORDER BY column_name";
$result = mysqli_query($connection, $sql);

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

// Close connection
mysqli_close($connection);
?>