How do i sort table by a link

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
Bonta_SWE
Forum Newbie
Posts: 14
Joined: Thu Sep 18, 2003 7:04 pm
Location: Sweden, Skåne

How do i sort table by a link

Post by Bonta_SWE »

Hi,
How do i sort a table by a link,
In my mysql database i have "Id, u_name, real_name, email, psw".

when i print the table into a html i have this code
$sql="select * from users order by id";

now i want by pressing a link on that page, it should sort for example
the u_name.

How do i do that ??

PS
excuse for my english
User avatar
Saethyr
Forum Contributor
Posts: 182
Joined: Thu Sep 25, 2003 9:21 am
Location: Wichita, Kansas USA
Contact:

Post by Saethyr »

I would do it as follows:

if ($_REQUEST["submit"] != "")
{

$OrderVar = $_REQUEST["submit"];
}
else {
$OrderVar = "id";
}
$sql="select * from users order by $OrderVar";

blah blah blah

then on your links for sort by just do
a href="thispage.php?submit=u_name">Username></a>
User avatar
Saethyr
Forum Contributor
Posts: 182
Joined: Thu Sep 25, 2003 9:21 am
Location: Wichita, Kansas USA
Contact:

Post by Saethyr »

Got to thinkig about this after I posted, I just posted a huge security flaw. I will think about this and post the fixed code after awhile. Don't know what the hell I was thinking earlier.

Saethyr
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Passing an "order by" value via GET is fine - but don't pass a column name on the general principle of not providing information about your database.

You could take GET values and map them to column names with a switch/case.

That just leaves sticking the appropriate hyperlink on the column headers.
Bonta_SWE
Forum Newbie
Posts: 14
Joined: Thu Sep 18, 2003 7:04 pm
Location: Sweden, Skåne

Post by Bonta_SWE »

Thanx Saethyr

Your code worked real fine, and it was very simple to understand.
Thanx again.

/Mattias
Post Reply