Click the Mark heading to switch between ascending and descending order. The live table below uses a strict two-value whitelist, so the requested direction can only become ASC or DESC.
| Name | Mark DESC |
|---|---|
| Tade Row | 88 |
| Marry Toeey | 88 |
| Gimmy | 88 |
| John Deo | 75 |
| Babby John | 69 |
| Krish Star | 60 |
| John Mike | 60 |
| Big John | 55 |
| Alex John | 55 |
SELECT name, mark
FROM student
WHERE class = 'Four'
ORDER BY mark DESC, name ASC;
The second sort column gives stable ordering when several students have the same mark.
SQL keywords and identifiers cannot be bound as PDO value parameters. Validate them against a small allow-list before placing them in the SQL text.
<?php
$direction = (isset($_GET['by']) && strtolower($_GET['by']) === 'desc') ? 'DESC' : 'ASC';
$query = "SELECT name, mark
FROM student
WHERE class = :class
ORDER BY mark $direction, name ASC";
$stmt = $dbo->prepare($query);
$stmt->execute([':class' => 'Four']);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
The older page used the removed mysql_query() / mysql_fetch_array() API. The modern example uses PDO and explicitly validates the only dynamic SQL keyword.
See also the PHP paging example.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Erkki | 15-03-2014 |
| How do you get rid of double or triple and so on "by=asc" "by=desc" lines on url line in the browser? Whenever you implement it in your own code the url line just generates more variables "by=asc&by=desc" an so on. | |
| phraglets | 03-02-2015 |
| do you have a sample of dynamic table that can display all the table in the database even if their field are different, with pagination | |
| smo | 06-02-2015 |
| You can download the plus admin script . Or check this page to list tables | |