Jump to content

ORDERING with php


chriscloyd

Recommended Posts

Im trying to make a link where people can order their mysql query from

heres my links
[code]
<a href="?sort=id">ID</a> <a href="?sort=first, last">Name</a> <a href="?sort=position">Position</a> <a href="?sort=email">Email</a> <a href="?sort=level">Level</a> - <a href="?type=ASC">ASC</a> <a href="?type=DESC">DESC</a>
[/code]

heres my code
[code]
<?php
if ($_GET['sort']) {
$sort = $_GET['sort'];
} else {
$sort = 'id';
}
if ($_GET['type']) {
$type = $_GET['type'];
} else {
$type = 'ASC';
}
$get_all_staff = mysql_query("SELECT * FROM users WHERE level IN('admin','support','sales','staff') ORDER BY '$sort' '$type'");
?>
[/code]
Link to comment
https://forums.phpfreaks.com/topic/33672-ordering-with-php/
Share on other sites

change a few things about your approach.

first:
instead of directly inputting the $_GET var in your query use a switch case so that a user couldnt modify the link to sort=or1=1 - which would show all of your table info
<a href="link.php?sort=positon">position</a>

then on your processing page do this
switch($_GET['sort']){
case 'position' :
$sort = 'position';
break;
default:
$sort = 'id';
break;
}

second:

seperate your query from the mysql comman, this will make it easier to tell what the problem is

$query = "select...";
mysql_query($query) or die (mysql_error()."<br />".$query);


third:
i like to concatenate my strings
$query = "SELECT field FROM table WHERE field = ". $var ." AND ...";

that makes it a lil easier to read, espically if you have an editor that will color yoru code
Link to comment
https://forums.phpfreaks.com/topic/33672-ordering-with-php/#findComment-157814
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.