Php order by syntax

PHP MySQL ORDER BY Clause

In this tutorial you will learn how to sort and display the data from a MySQL table in ascending or descending order using PHP.

Ordering the Result Set

The ORDER BY clause can be used in conjugation with the SELECT statement to see the data from a table ordered by a specific field. The ORDER BY clause lets you define the field name to sort against and the sort direction either ascending or descending.

The basic syntax of this clause can be given with:

Let’s make a SQL query using the ORDER BY clause in SELECT statement, after that we will execute this query through passing it to the PHP mysqli_query() function to get the ordered data. Consider the following persons table inside the demo database:

+----+------------+-----------+----------------------+ | id | first_name | last_name | email | +----+------------+-----------+----------------------+ | 1 | Peter | Parker | peterparker@mail.com | | 2 | John | Rambo | johnrambo@mail.com | | 3 | Clark | Kent | clarkkent@mail.com | | 4 | John | Carter | johncarter@mail.com | | 5 | Harry | Potter | harrypotter@mail.com | +----+------------+-----------+----------------------+

The PHP code in the following example selects all rows from the persons table and sorts the result by the first_name column in the alphabetically ascending order.

Example

 // Attempt select query execution with order by clause $sql = "SELECT * FROM persons ORDER BY first_name"; if($result = mysqli_query($link, $sql)) < if(mysqli_num_rows($result) >0)< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; while($row = mysqli_fetch_array($result))< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
idfirst_namelast_nameemail
" . $row['id'] . "" . $row['first_name'] . "" . $row['last_name'] . "" . $row['email'] . "
"; // Close result set mysqli_free_result($result); > else < echo "No records matching your query were found."; >> else < echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); >// Close connection mysqli_close($link); ?>
connect_error); > // Attempt select query execution with order by clause $sql = "SELECT * FROM persons ORDER BY first_name"; if($result = $mysqli->query($sql))< if($result->num_rows > 0)< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; while($row = $result->fetch_array())< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
idfirst_namelast_nameemail
" . $row['id'] . "" . $row['first_name'] . "" . $row['last_name'] . "" . $row['email'] . "
"; // Free result set $result->free(); > else < echo "No records matching your query were found."; >> else< echo "ERROR: Could not able to execute $sql. " . $mysqli->error; > // Close connection $mysqli->close(); ?>
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); > catch(PDOException $e)< die("ERROR: Could not connect. " . $e->getMessage()); > // Attempt select query execution try< $sql = "SELECT * FROM persons ORDER BY first_name"; $result = $pdo->query($sql); if($result->rowCount() > 0)< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; while($row = $result->fetch())< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
idfirst_namelast_nameemail
" . $row['id'] . "" . $row['first_name'] . "" . $row['last_name'] . "" . $row['email'] . "
"; // Free result set unset($result); > else < echo "No records matching your query were found."; >> catch(PDOException $e)< die("ERROR: Could not able to execute $sql. " . $e->getMessage()); > // Close connection unset($pdo); ?>

After ordering the result, the result set will look something like this:

+----+------------+-----------+----------------------+ | id | first_name | last_name | email | +----+------------+-----------+----------------------+ | 3 | Clark | Kent | clarkkent@mail.com | | 5 | Harry | Potter | harrypotter@mail.com | | 2 | John | Rambo | johnrambo@mail.com | | 4 | John | Carter | johncarter@mail.com | | 1 | Peter | Parker | peterparker@mail.com | +----+------------+-----------+----------------------+

Tip: By default the ORDER BY clause sort the results in ascending order. If you want to sort the records in a descending order, you can use the DESC keyword.

Читайте также:  Bootstrap grid only css

Источник

PHP MySQL Use The ORDER BY Clause

The ORDER BY clause is used to sort the result-set in ascending or descending order.

The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

To learn more about SQL, please visit our SQL tutorial.

Select and Order Data With MySQLi

The following example selects the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column:

Example (MySQLi Object-oriented)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>

$sql = «SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname»;
$result = $conn->query($sql);

if ($result->num_rows > 0) // output data of each row
while($row = $result->fetch_assoc()) echo «id: » . $row[«id»]. » — Name: » . $row[«firstname»]. » » . $row[«lastname»]. «
«;
>
> else echo «0 results»;
>
$conn->close();
?>

Code lines to explain from the example above:

First, we set up the SQL query that selects the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column. The next line of code runs the query and puts the resulting data into a variable called $result.

Then, the function num_rows() checks if there are more than zero rows returned.

If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, firstname and lastname columns.

The following example shows the same as the example above, in the MySQLi procedural way:

Example (MySQLi Procedural)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

Читайте также:  MYCRUD

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>

$sql = «SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname»;
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) // output data of each row
while($row = mysqli_fetch_assoc($result)) echo «id: » . $row[«id»]. » — Name: » . $row[«firstname»]. » » . $row[«lastname»]. «
«;
>
> else echo «0 results»;
>

You can also put the result in an HTML table:

Example (MySQLi Object-oriented)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>

$sql = «SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname»;
$result = $conn->query($sql);

if ($result->num_rows > 0) echo «

«;
// output data of each row
while($row = $result->fetch_assoc()) echo «

«;
>
echo «

ID Name
«.$row[«id»].» «.$row[«firstname»].» «.$row[«lastname»].»

«;
> else echo «0 results»;
>
$conn->close();
?>

Select Data With PDO (+ Prepared Statements)

The following example uses prepared statements.

Here we select the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column, and it will be displayed in an HTML table:

Example (PDO)

class TableRows extends RecursiveIteratorIterator <
function __construct($it) <
parent::__construct($it, self::LEAVES_ONLY);
>

function current() return «

» . parent::current(). «

«;
>

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDBPDO»;

try $conn = new PDO(«mysql:host=$servername;dbname=$dbname», $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare(«SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname»);
$stmt->execute();

Источник

Предложение ORDER BY PHP MySQL

В этом уроке вы узнаете, как с помощью PHP сортировать и отображать данные из таблицы MySQL в порядке возрастания или убывания.

Фильтрация записей в порядке возрастания или убывания

Предложение ORDER BY используется для сортировки набора результатов в порядке возрастания или убывания.

Предложение ORDER BY по умолчанию сортирует записи в порядке возрастания. Чтобы отсортировать записи в порядке убывания, используйте ключевое слово DESC :

Код РНР сортировки записей в алфавитном порядке

Давайте сделаем SQL-запрос, используя предложение ORDER BY , после чего мы выполним этот запрос, передав его функции PHP mysqli_query() для получения упорядоченных данных. Рассмотрим следующую таблицу persons в базе данных demo:

Выбор данных из таблиц базы данных MySQL

Код РНР в следующем примере выбирает все строки из таблицы persons и сортирует результат в столбце first_name в алфавитном порядке возрастания:

Example

 // Попытка выполнения запроса select с предложением order by $sql = "SELECT * FROM persons ORDER BY first_name"; if($result = mysqli_query($link, $sql)) < if(mysqli_num_rows($result) >0)< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; while($row = mysqli_fetch_array($result))< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
idfirst_namelast_nameemail
" . $row['id'] . "" . $row['first_name'] . "" . $row['last_name'] . "" . $row['email'] . "
"; // Закрываем набор результатов mysqli_free_result($result); > else < echo "Не найдено ни одной записи, соответствующей вашему запросу."; >> else < echo "ОШИБКА: не удалось выполнить $sql. " . mysqli_error($link); >// Закрываем соединение mysqli_close($link); ?>
connect_error); > // Попытка выполнения запроса select с предложением order by $sql = "SELECT * FROM persons ORDER BY first_name"; if($result = $mysqli->query($sql))< if($result->num_rows > 0)< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; while($row = $result->fetch_array())< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
idfirst_namelast_nameemail
" . $row['id'] . "" . $row['first_name'] . "" . $row['last_name'] . "" . $row['email'] . "
"; // Free result set $result->free(); > else < echo "Не найдено ни одной записи, соответствующей вашему запросу."; >> else< echo "ОШИБКА: не удалось выполнить $sql. " . $mysqli->error; > // Закрываем соединение $mysqli->close(); ?>
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); > catch(PDOException $e)< die("ОШИБКА: не удалось подключиться. " . $e->getMessage()); > // Попытка выполнения запроса select try< $sql = "SELECT * FROM persons ORDER BY first_name"; $result = $pdo->query($sql); if($result->rowCount() > 0)< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; while($row = $result->fetch())< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
idfirst_namelast_nameemail
" . $row['id'] . "" . $row['first_name'] . "" . $row['last_name'] . "" . $row['email'] . "
"; // Free result set unset($result); > else < echo "Не найдено ни одной записи, соответствующей вашему запросу."; >> catch(PDOException $e)< die("ОШИБКА: не удалось выполнить $sql. " . $e->getMessage()); > // Закрываем соединение unset($pdo); ?>

Результат выполнения скрипта будет выглядеть примерно так:

+----+------------+-----------+----------------------+ | id | first_name | last_name | email | +----+------------+-----------+----------------------+ | 3 | Clark | Kent | clarkkent@mail.com | | 5 | Harry | Potter | harrypotter@mail.com | | 2 | John | Rambo | johnrambo@mail.com | | 4 | John | Carter | johncarter@mail.com | | 1 | Peter | Parker | peterparker@mail.com | +----+------------+-----------+----------------------+

Объяснение кода из приведенного выше примера:

Сначала мы настраиваем SQL-запрос, который выбирает столбцы id, first_name, last_name и email из таблицы persons. Записи будут отсортированы по столбцу first_name. Следующая строка кода выполняет запрос и помещает полученные данные в переменную с именем $result.

Затем функция mysqli_num_rows() проверяет, было ли возвращено строк больше нуля.

Если возвращается более нуля строк, функция mysqli_fetch_array помещает все результаты в ассоциативный массив, который мы можем просмотреть. В цикле while() через результирующий набор выводятся данные из столбцов id, first_name, last_name и email.

Выборка данных стиле PDO (+ подготовленные операторы)

В следующем примере используются подготовленные операторы.

Он выбирает столбцы id, first_name, last_name и email из таблицы persons, где last_name=’Carter’, и отображает их в таблице HTML:

Пример

"; echo "IdИмяФамилияE-mail"; class TableRows extends RecursiveIteratorIterator < function __construct($it) < parent::__construct($it, self::LEAVES_ONLY); >function current() < return "" . parent::current(). ""; > function beginChildren() < echo ""; > function endChildren() < echo "" . "\n"; > > $serverName = "localhost"; $userName = "root"; $password = ""; $dbName = "demo"; try < $conn = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT id, first_name, last_name, email FROM persons ORDER BY last_name"); $stmt->execute(); // поместить результат в ассоциативный массив $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) < echo $v; >> catch(PDOException $e) < echo "Ошибка: " . $e->getMessage(); > $conn = null; echo ""; ?>

Результат выполнения кода:

Id Имя Фамилия E-mail
4 John Carter johncarter@mail.com
3 Clark Kent clarkkent@mail.com
1 Peter Parker peterparker@mail.com
5 Harry Potter harrypotter@mail.com
2 John Rambo johnrambo@mail.com
6 Ron Weasley ronweasley@mail.com

Источник

Оцените статью