Dynamic SQL ORDER BY from PHP

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.

NameMark DESC
Tade Row88
Marry Toeey88
Gimmy88
John Deo75
Babby John69
Krish Star60
John Mike60
Big John55
Alex John55

SQL ORDER BY

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.

Allow a user to choose ASC or DESC safely

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.




Subscribe to our YouTube Channel here



plus2net.com
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




SQL Video Tutorials










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer