Page 1 of 1

Sorting Results

Posted: Thu Oct 21, 2004 9:16 am
by billybonz81
does anyone know of a way of using hyperlinks to sort the results of a query?

Posted: Thu Oct 21, 2004 9:26 am
by pickle
Not 100% sure what you mean, but I think you'd need to pass the sorting field(s) in the URL.

So, for example, if you want to sort by the field 'age', you'd have a link that looks like:

Code: Select all

<a href = 'this_page.php?sort=age'>Age</a>
Then in the page, just have your query ordered by $_GET['sort']

Posted: Thu Oct 21, 2004 9:26 am
by kettle_drum
Have the link include how you want to sort it and then use this information to produce the sql query.

Code: Select all

$query = "SELECT * FROM blah";
if(isset($_GET['sort'])){
   if($_GET['sort']=='title'){
      $query .= " ORDER BY title";
   }else{
      $query .= " ORDER BY id";
   }
}
You can make this as complex or simple as you like allowing them to be sorted in different directions and fields.

still having problems!

Posted: Thu Oct 21, 2004 10:28 am
by billybonz81
nigma | Help us, help you. Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

ok i did it and now its giving me the following error:

You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc LIMIT 0, 10' at line 1

here is my code:

Code: Select all

$query_Recordset1 = "SELECT * FROM `data`";
if (isset($_GET['sort'])) {
	if($_GET['sort'] =='id') {
		$query_Recordset1 .= " ORDER BY id asc";
	}else {
		$query_Recordset1 .= " ORDER BY beds asc";
		}
	}
if (isset($_GET['sort2'])) {
	if($_GET['sort2'] =='id') {
		$query_Recordset1 .= " ORDER BY id asc desc";
	}else {
		$query_Recordset1 .= " ORDER BY beds desc";
		}
	}
$query_limit_Recordset1 = sprintf("%s LIMIT %d, %d", $query_Recordset1, $startRow_Recordset1, $maxRows_Recordset1);
nigma | Help us, help you. Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Thu Oct 21, 2004 10:55 am
by pickle
Line 11 - you can't order by asc, then desc in the same column

If I ever get errors like that, I usually output the whole query and look at it - easier to see what's wrong.