Page 1 of 1

MYSQL query order by and php variables

Posted: Wed Apr 04, 2007 9:21 pm
by AnneBonny
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Sorry if I am being dense but......

below is relevant extracted code from a web page
--------------------------------------------------

Code: Select all

<form method="get">
<input type=text name="SortBy" value="TimeOnline">
<input type=submit value="Submit">
</form>



<?php



	echo $_POST['SortBy'];
   	echo $_REQUEST['SortBy'];
	import_request_variables('p', 'p_');
   	echo $p_SortBy;


$sql = "SELECT CharName,LastLogin,Race,Subrace,TimeOnline,OverallLevel,Deaths,Class1,Class2,Class3,Abil_STR,Abil_CON,Abil_DEX,Abil_INT,Abil_WIS,Abil_CHA  FROM table_character order by '$p_SortBy' DESC";


echo $sql;

?>

comments:
-----------------
echo $p_SortBy; returns the correct value
echo $sql; returns a value of '' for $p_SortBy

if I replace $p_SortBy with a valid table column it sorts correctly
so my question is can I not use a php variable as a parameter for order by in a sql statement - it appears that way?

What I am trying to accomplish is to give an option to choose sort order in a post


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Wed Apr 04, 2007 10:16 pm
by jwalsh
Use Code and PHP tags in your post please.


Yes, you could use a form to change the sort order of your query. The PHP variable should contain the name of the column you wish to sort by.

Code: Select all

// Assume $_POST['p_SortBy'] is "LastLogin"

$sql = "SELECT CharName,LastLogin,Race,Subrace,TimeOnline,OverallLevel,Deaths,Class1,Class2,Class3,Abil_STR,Abil_CON,Abil_DEX,Abil_INT,Abil_WIS,Abil_CHA FROM table_character order by '{$_POST['p_SortBy']' DESC";
... would sort your query by LastLogin.

Note, there are security issues here... major ones, but for simplicity I haven't fixed those.