Thanks to folks here on stackoverflow I have mastered most aspects of database (sqlite) control using php in a matter of days!!! And managed to build a basic crud cms. I am now making minor improvements and stuck on ‘saving database sort in a session’. When I click off the page and then return, the session is not saved. I have got so far and this seems a frustrating stumbling block. This is what I have:
session_start();
$_SESSION['sort'] = $_GET['sort'];
$savedsort = $_SESSION['sort']; // store session data
if(!empty($_GET['sort']) && ctype_alnum(trim($_GET['sort'])))
$sort = trim($_GET['sort']);?> ///if page is empty
//links to sort data
<h2><?php echo $savedsort;?></h2>
<table border="0" align="center" cellpadding="8" cellspacing="0" id="show"><tr><th width="5"><a href="?sort=id">ID</a></th><th>IMG</th><th><a href="?sort=name">NAME</a></th>
<th width="10"><a href="?sort=cat">CAT</a></th></tr>
//query string
///////////////////////////////////////sort columns ////////////////////////////////
if($sort == $savedsort){
$result = $db->query("SELECT * FROM '$table1' ORDER BY '$savedsort' ");
}
else{$result = $db->query("SELECT * FROM '$table1' ORDER BY id ");}
//////////////////////////////////////////////////////////////////////////////////////
foreach($result as $row){
…any pointers greatly appreciated. Thanks in advance.
Saves in session variable now, thanks but will not update query string
session_start();
if (isset($_GET['srt']))
{ $_SESSION['srt'] = $_GET['srt']; }
$srt = $_SESSION['srt'];
<tr><th width="5"><a href="?srt=id">ID</a></th><th>IMG</th><th><a href="?srt=name">NAME</a></th><th width="10"><a href="?srt=menu">CAT</a></th>........
$srtd = $db->query("SELECT * FROM '$table1' ORDER BY '$srt' "); ////////////////////////////////////////////////////////////////////////////////////// foreach($srtd as $row){ $id=$row['id'];
BUT this method works : is the above code ok?
///////////////////////////////////////sort columns ////////////////////////////////
if ($srt=='name'){$srtd = $db->query("SELECT * FROM '$table1' ORDER BY name ");}
elseif($srt=='id'){$srtd = $db->query("SELECT * FROM '$table1' ORDER BY id ");}
elseif($srt=='menu'){$srtd = $db->query("SELECT * FROM '$table1' ORDER BY menu ");}
else{$srtd = $db->query("SELECT * FROM '$table1' ORDER BY id ");}
//////////////////////////////////////////////////////////////////////////////////////
Thanks for that Nick 😉 The strange thing is that I used single quotes in this query and it works $dropdown = $db->query("SELECT * FROM '$table2' WHERE menu = '$menu'"); but I will use back ticks from now on
You are assiging
$_SESSION['sort'] = $_GET['sort'];every time you visit the page, and so if$_GET['sort']isn’t set then it’ll just change$_SESSION['sort']to a null value.Change it to:
and it should work
Edit:
Your query should be updated to:
Note the use of back ticks ` instead of single quotes. Back ticks are used for table names, quotes are used for strings.