Skip to content
PHP Logo

What SQL command can be used to order the output of a database table in PHP?

To order the output of a database table in PHP, you can use the SQL command "ORDER BY" followed by the column you want to sort by. For example, if you want to sort a table named "users" by the "name" column in ascending order, you would use "ORDER BY name ASC". If you want to sort in descending order, you would use "ORDER BY name DESC".

php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');

// Prepare and execute a query to select data from the table 'users' and order it by the 'name' column in ascending order
$stmt = $pdo->prepare("SELECT * FROM users ORDER BY name ASC");
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();

// Loop through the results and display them
foreach($results as $row) {
    echo $row['name'] . "<br>";
}