PHP MySQL Query Use ORDER BY
From w3cyberlearnings
Contents |
PHP MySQL SELECT Use ORDER BY
In the SELECT statement can use the ORDER BY to order the return select statement.
Syntax
- Return the SELECT statement order by the first_name.
- ORDER BY DESC (use order by descending:Z-A or largest to the smallest), it default option when not define.
- ORDER BY ASC (use order by ascending:A-Z or smallest to the largest)
$sel_query = 'SELECT first_name, last_name FROM student ORDER BY first_name '; $result = mysql_query($sel_query, $connection);
Example 1
<?php define('HOST', 'localhost'); define('USER', 'root'); define('PASS', 'yeething'); define('DBNAME', 'woowood'); $connection = mysql_connect(HOST, USER, PASS); if (!$connection) { die("can not connect to the server!<br/>"); } else { $rdb = mysql_select_db(DBNAME); if (!$rdb) { die("The " . DBNAME . "database could not be selected"); } else { $sel_query = 'SELECT first_name, last_name FROM student ORDER BY first_name'; $result = mysql_query($sel_query, $connection) or die(mysql_error($connection)); echo '<table border="1">'; echo '<tr><th>First Name</th><th>Last Name</th></tr>'; while ($row = mysql_fetch_assoc($result)) { echo '<tr>'; foreach ($row as $value) { echo '<td>' . $value . '</td>'; } echo "</tr>"; } echo '</table>'; } } mysql_close($connection); ?>