I am doing a inventory system for someone. I want to be able to click on a link in the table header and cause it to sort by PN and ASC. Then if I click PN again, by DESC. But I also want to order it by description and do the same thing. Here is my code so far. I cannot figure out how to let it swap directions (ASC, DESC) easily.
if (!isset($cd))
{
$cd = 0;
}
if (isset($_SESSION['direction']) && $cd == 1)
{
if ($_SESSION['direction'] == 'DESC')
{
$_SESSION['direction'] = 'ASC';
$cd = 0;
} elseif ($_SESSION['direction'] == 'ASC')
{
$_SESSION['direction'] = 'DESC';
$cd = 0;
}
} else
{
$_SESSION['direction'] = 'ASC';
}
if (isset($_REQUEST['sort']))
{
if ($_REQUEST['sort'] == 'pn')
{
$sql=mysql_query("select * from inventory ORDER BY pn {$_SESSION['direction']}");
} elseif ($_REQUEST['sort'] == 'description') {
$sql=mysql_query("select * from inventory ORDER BY description {$_SESSION['direction']}");
} elseif ($_REQUEST['sort'] == 'wholesale') {
$sql=mysql_query("select * from inventory ORDER BY wholesale {$_SESSION['direction']}");
} elseif ($_REQUEST['sort'] == 'list') {
$sql=mysql_query("select * from inventory ORDER BY list {$_SESSION['direction']}");
} elseif ($_REQUEST['sort'] == 'stock') {
$sql=mysql_query("select * from inventory ORDER BY stock {$_SESSION['direction']}");
} elseif ($_REQUEST['sort'] == 'location') {
$sql=mysql_query("select * from inventory ORDER BY location {$_SESSION['direction']}");
}
} else {
$sql=mysql_query("select * from inventory ORDER BY pn {$_SESSION['direction']}");
}
echo "<center><table class=\"myTable\">
<th><a href=\"inventory.php?mode=list&sort=pn\">PN</a></th><th><a href=\"inventory.php?mode=list&sort=description\">Description</a></th><th><a href=\"inventory.php?mode=list&sort=wholesale\">Wholesale</th><th><a href=\"inventory.php?mode=list&sort=list\">List</th><th><a href=\"inventory.php?mode=list&sort=stock\">Stock</th><th><a href=\"inventory.php?mode=list&sort=location\">Location</th><th>Links</th>";
while ($result=mysql_fetch_array($sql))
{
echo "<tr><td>{$result['pn']}</td><td>{$result['description']}</td><td>{$result['wholesale']}</td><td>{$result['list']}</td><td>{$result['stock']}</td><td>{$result['location']}</td><td>[<a href='inventory.php?mode=edit&id={$result['id']}'>Edit</a>] [<a href='inventory.php?mode=delete&id={$result['id']}'>Delete</a>] [<a href='orders.php?mode=list_c&id={$result['id']}'>View Orders</a>]</tr>";
}
echo "</table></center>";
OMG.
Look at this much shortened code of what You have:
But You should not use
mysql_*functions, learnPDOor at leastmysqli_*