PHP MySQL — SELECT, ORDER BY
When the database has some records in it, you can retrieve the stored information with the SELECT statement.
A SELECT query returns rows selected from one or more tables.
SELECT column_name(s) FROM table_name
— » column_name(s) » — is the name of the column (or columns) you want to select.
To select multiple columns, add them separated by a comma:
SELECT column1, column2, column3 FROM table_name
To sellect all columns, just put an asterisk (*):
SELECT * FROM table_name
To send the SQL statement to the MySQL database and retrieve the data returned, use the query() method of the mysqli object.
When is used with SELECT queries, this method returns a result object that stores the rows of data, or False on error.
To provide one row of data at a time, you can use a method of the result object called fetch_assoc .
The fetch_assoc() method returns an associative array that corresponds to the fetched row, the keys of the elements are the name of the columns. With a while() loop we can get the data of each row stored in that array.
To get the numbers of rows returned by a SELECT query, use the num_rows method, applied to the result object.
— The fallowing example selects and displays the data stored in the «id», «name» and «pass» columns in the «users» table.
// SELECT sql query $sql = "SELECT `id`, `name`, `pass` FROM `users`"; // perform the query and store the result $result = $conn->query($sql); // if the $result contains at least one row if ($result->num_rows > 0) < // output data of each row from $result while($row = $result->fetch_assoc()) < echo '
id: '. $row['id']. ' - name: '. $row['name']. ' - pass: '. $row['pass']; > > else < echo '0 results'; >$conn->close(); ?>
— This example stores the data (the result object) returned by the query() method in the $result variable, uses the «num_rows» method to check if $result contains at least one row. Then, with a while() loop loops through all the records in the result object, using the «fetch_assoc()» method to store the data of each row in an Array in the $row variable.
Each call to fetch_assoc() returns the next row in the recordset.
To print the value of each row, we use the PHP $row variable and the key of each column ($row[‘id’], . ).
The code above will output:
id: 1 — name: Marius — pass: faith
id: 2 — name: MarPlo — pass: peace
id: 3 — name: I_AM — pass: love
id: 4 — name: PloMar — pass: love_light
The asterisk (*) can be used to select all column: «SELECT * FROM table_name», but is better to be explicit about which columns are selected. The selecting process can be faster if only the columns you will use are fetched.
The LIMIT option
SELECT column_names FROM table_name LIMIT skip_count, show_count
» skip_count » is optional, it tells the database how many rows to skip from results.
» show_count » sets the maximum number of records to return.
— Example :
// SELECT sql query $sql sb">LIMIT 2"; // perform the query and store the result $result = $conn->query($sql); // if the $result contains at least one row if ($result->num_rows > 0) < // output data of each row from $result while($row = $result->fetch_assoc()) < echo '
id: '. $row['id']. ' - name: '. $row['name']. ' - pass: '. $row['pass']; > > else < echo '0 results'; >$conn->close(); ?>
ORDER BY
SELECT column_names FROM table_name ORDER BY col_name ASC|DESC
» col_name » can be a single column, a comma separated list of columns, or an expression such as RAND(), which randomizes the order.
When ordering by more than one column, the second column is only used if the values in the first column are equal.
The default sort order is ascending (ASC) (a–z, 0–9), and ASC option can be omitted. DESC (descending) reverses the order.
— Example :
// SELECT sql query $sql sb">ORDER BY `name`"; // perform the query and store the result $result = $conn->query($sql); // if the $result contains at least one row if ($result->num_rows > 0) < // output data of each row from $result while($row = $result->fetch_assoc()) < echo '
id: '. $row['id']. ' - name: '. $row['name']. ' - pass: '. $row['pass']; > > else < echo '0 results'; >$conn->close(); ?>
— This code selects all the data stored in the «users» table, and sorts the result in alphabetical order by the «name» column.
This example above will output:
id: 3 — name: I_AM — pass: love
id: 1 — name: Marius — pass: faith
id: 2 — name: MarPlo — pass: peace
id: 4 — name: PloMar — pass: love_light
• You can use ORDER BY with LIMIT option.
Example: «SELECT `id`, `name`, `pass` FROM `users` ORDER BY `name` LIMIT 2»
• To eliminate duplicate rows from the results, use the DISTINCT option:
SELECT DISTINCT column_names FROM table_name
— If you want to learn how to select values from two MySQL tables with a single query, see the tutorial: Select in two MySQL tables.
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»;
?php
// 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»;
?php
// 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»;
?php
// 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 «
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 «
«;
>
$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();