Sort and order php mysql

Posted By: Ian on Dec 19, 2011 in Blog, PHP
Last modified on November 20th, 2013 at 10:27 am,

During the building of Banner Bar version 2 i needed sort and direction to be carried forward to each page and this is what i came up with.
So for anyone looking hope it helps. I have included a full working demo and download link below anyone wanting the mysql table just contact me.
Using the array stops anyone trying to include any other words in the get order by and if they try the script tells them it’s not allowed.
Be sure to set a default sort order which i have chosen ID then from there the sessions take over.

<?php
//------ Begin sort and order ------//
if (isset($_GET["order"])) {
$order = mysql_real_escape_string($_GET["order"]);
$allowed_columns = array(
'id',
'impressions',
'clicks',
'timer',
'expires',
'creationDate'
);
if (in_array($order, $allowed_columns)) {
$_SESSION['order'] = $order;
} else {
$_SESSION['order'] = "id";
die("<p>That is not allowed!</p>");
}
}
if (isset($_SESSION['order'])) {
$order = $_SESSION['order'];
} elseif (!isset($_SESSION['order'])) {
$order = "id";
}
if ($_GET['dir'] == 'DESC') {
$dir = 'DESC';
$_SESSION['dir'] = "DESC";
$dir_link = 'ASC';
} else {
$dir = 'ASC';
$_SESSION['dir'] = "ASC";
$dir_link = 'DESC';
}
$page_link = $_SESSION['dir'];
//------ End sort and order ------//
?>

$result = mysql_query("SELECT * FROM demoTable ORDER BY $order $dir");

<?php echo '<a href="index.php?order=id&amp;dir='.$dir_link.'">ID</a>'; ?>
<?php echo '<a href="index.php?order=name&amp;dir='.$dir_link.'">Name</a>'; ?>
<?php echo '<a href="index.php?order=age&amp;dir='.$dir_link.'">Age</a>'; ?>

<?php
$show_page = $curren_page + 1;
$url = "index.php?page=" . $i."&amp;order=".$order."&amp;dir=" . $page_link;
echo "<a href=\"$url\">$i</a>";
?>

For a Working example Click hereDownload working example

AnonymousIan.J.Gough

Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125