Php mysqli query order by

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»;

// 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

Источник

Php mysqli query order by

Connected successfully EMP ID :3 EMP NAME : jai EMP SALARY : 90000 ——————————— EMP ID :2 EMP NAME : karan EMP SALARY : 40000 ——————————— EMP ID :1 EMP NAME : ratan EMP SALARY : 9000 ———————————

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Читайте также:  Edit field in html
Оцените статью