Re: sorting columns in a client-side page
- From: gordonb.o6v7l@xxxxxxxxxxx (Gordon Burditt)
- Date: Tue, 30 Dec 2008 03:42:50 -0600
What is an easy way to produce the headings for columns in an html table
that are sortable by clicking on them please?
I see these quite often and find them to be very useful, yet the code to
produce them is elusive for me. I am a beginner at all of php, mysql and
html and know nothing of css, and hope to find some coding examples that
are relatively easy to understand and incorporate into the existing
elementary-level code below.
This approach is not intended to be a general mechanism that takes
a table it's never heard of before. The page knows the columns and
how to label them.
I prefer to let the database do the sorting. I typically define a
variable like 'sort', and the links that change the sort order for
the page mypage.php might look like mypage.php?sort=id or
mypage.php?sort=lastname . Each keyword represents a sort order
(and not necessarily only on one column). Keywords are arbitrary
but for ease of remembering what they do, they sort of describe the
ordering in one "word".
One of the steps in mypage.php is to look at the value of $_GET['sort']
or $_POST['sort'], depending on the form, and turn it into an ORDER
BY clause for a SQL statement in the variable $order, usually using
a big switch. In order to avoid SQL injection, the value of
$_GET['sort'] must match one of a small number of legal values in
the switch, or if it doesn't, you get the default order, which might
be none or one of the other sort orders. The final value of $order
is one of the constant values assigned to it in the code, and the
value of $_GET['sort'] selects which one.
$order = ''; /* default */
if (isset($_GET['sort'])) {
$o = $_GET['sort'];
switch($o) {
case 'id': $order = 'ORDER BY id desc'; break;
case 'lastname': $order = 'ORDER BY lastname, firstname'; break;
}
}
Then when you get ready to do the query, you substitute $order
into the query in the right place.
$query = "SELECT id, lastname, firstname FROM table $order";
Then run the query.
Since the query may involve joins of several tables, the value of $order
is closely tied to the query being done.
.
- Follow-Ups:
- Re: sorting columns in a client-side page
- From: Bill H
- Re: sorting columns in a client-side page
- References:
- sorting columns in a client-side page
- From: Greg Russell
- sorting columns in a client-side page
- Prev by Date: Re: identify $handles in $resource ?
- Next by Date: Re: sorting columns in a client-side page
- Previous by thread: Re: sorting columns in a client-side page
- Next by thread: Re: sorting columns in a client-side page
- Index(es):
Relevant Pages
|