Generating Click to Sort Table Headings

18.12.1 Problem

You want to display a query result in a web page as a table that allows the user to select which column to sort the table rows by.

18.12.2 Solution

Make each column heading a hyperlink that redisplays the table, sorted by the corresponding column.

18.12.3 Discussion

When a web script runs, it can determine what action to take by querying its environment to find out what parameters are present and what their values are. In many cases these parameters come from a user, but there's no reason a script cannot add parameters to URLs itself. This is one way a given invocation of a script can send information to the next invocation. The effect is that the script communicates with itself by means of URLs that it generates to cause specific actions. An application of this technique is for showing the result of a query such that a user can select which column of the result to use for sorting the display. This is done by making the column headers active links that redisplay the table, sorted by the selected column.

The examples here use the mail table, which looks like this:

mysql> SELECT * FROM mail;
+---------------------+---------+---------+---------+---------+---------+
| t | srcuser | srchost | dstuser | dsthost | size |
+---------------------+---------+---------+---------+---------+---------+
| 2001-05-11 10:15:08 | barb | saturn | tricia | mars | 58274 |
| 2001-05-12 12:48:13 | tricia | mars | gene | venus | 194925 |
| 2001-05-12 15:02:49 | phil | mars | phil | saturn | 1048 |
| 2001-05-13 13:59:18 | barb | saturn | tricia | venus | 271 |
| 2001-05-14 09:31:37 | gene | venus | barb | mars | 2291 |
| 2001-05-14 11:52:17 | phil | mars | tricia | saturn | 5781 |
| 2001-05-14 14:42:21 | barb | venus | barb | venus | 98151 |
| 2001-05-14 17:03:01 | tricia | saturn | phil | venus | 2394482 |
| 2001-05-15 07:17:48 | gene | mars | gene | saturn | 3824 |
| 2001-05-15 08:50:57 | phil | venus | phil | venus | 978 |
| 2001-05-15 10:25:52 | gene | mars | tricia | saturn | 998532 |
| 2001-05-15 17:35:31 | gene | saturn | gene | mars | 3856 |
| 2001-05-16 09:00:28 | gene | venus | barb | mars | 613 |
| 2001-05-16 23:04:19 | phil | venus | barb | venus | 10294 |
| 2001-05-17 12:49:23 | phil | mars | tricia | saturn | 873 |
| 2001-05-19 22:21:51 | gene | saturn | gene | venus | 23992 |
+---------------------+---------+---------+---------+---------+---------+

To retrieve the table and display its contents as an HTML table, you can use the techniques discussed in Recipe 17.4. Here we'll use those same concepts but modify them to produce "click to sort" table column headings.

A "plain" HTML table would include a row of column headers consisting only of the column names:

 t
 srcuser
 srchost
 dstuser
 dsthost
 size

To make the headings active links that reinvoke the script to produce a display sorted by a given column name, we need to produce a header row that looks like this:

 <a href="<TT><I>script_name</I></TT>?sort=t">t</a>
 <a href="<TT><I>script_name</I></TT>?sort=srcuser">srcuser</a>
 <a href="<TT><I>script_name</I></TT>?sort=srchost">srchost</a>
 <a href="<TT><I>script_name</I></TT>?sort=dstuser">dstuser</a>
 <a href="<TT><I>script_name</I></TT>?sort=dsthost">dsthost</a>
 <a href="<TT><I>script_name</I></TT>?sort=size">size</a>

To generate such headings, the script needs to know the names of the columns in the table, as well as its own URL. Recipe 9.6 and Recipe 18.2 show how to obtain this information using query metadata and information in the script's environment. For example, in PHP, a script can generate the header row for the columns in a given query like this:

$self_path = get_self_path ( );
print ("
");
for ($i = 0; $i < mysql_num_fields ($result_id); $i++)
{
 $col_name = mysql_field_name ($result_id, $i);
 printf ("<a href="">%s</a>
",
 $self_path,
 urlencode ($col_name),
 htmlspecialchars ($col_name));
}
print ("
");

The following script, clicksort.php, implements this kind of table display. It checks its environment for a sort parameter that indicates which column to use for sorting. The script then uses the parameter to construct a query of the following form:

SELECT * FROM $tbl_name ORDER BY $sort_col LIMIT 50

(If no sort parameter is present, the script uses ORDER BY 1 to produce a default of sorting by the first column.) The LIMIT clause is simply a precaution to prevent the script from dumping huge amounts of output if the table is large.

Here's what the script looks like:



Table: " . htmlspecialchars ($tbl_name) . "

"); print ("

Click on a column name to sort the table by that column.

"); # Get the name of the column to sort by (optional). If missing, use # column one. If present, perform simple validation on column name; # it must consist only of alphanumeric or underscore characters. $sort_col = get_param_val ("sort"); # column name to sort by (optional) if (!isset ($sort_col)) $sort_col = "1"; # just sort by first column else if (!ereg ("^[0-9a-zA-Z_]+$", $sort_col)) die (htmlspecialchars ("Column name $sort_col is invalid")); # Construct query to select records from the named table, optionally sorting # by a particular column. Limit output to 50 rows to avoid dumping entire # contents of large tables. $query = "SELECT * FROM $tbl_name"; $query .= " ORDER BY $sort_col"; $query .= " LIMIT 50"; $result_id = mysql_query ($query, $conn_id); if (!$result_id) die (htmlspecialchars (mysql_error ($conn_id))); # Display query results as HTML table. Use query metadata to get column # names, and display names in first row of table as hyperlinks that cause # the table to be redisplayed, sorted by the corresponding table column. print (" "); $self_path = get_self_path ( ); print (" "); for ($i = 0; $i < mysql_num_fields ($result_id); $i++) { $col_name = mysql_field_name ($result_id, $i); printf (" ", $self_path, urlencode ($col_name), htmlspecialchars ($col_name)); } print (" "); while ($row = mysql_fetch_row ($result_id)) { print (" "); for ($i = 0; $i < mysql_num_fields ($result_id); $i++) { # encode values, using   for empty cells $val = $row[$i]; if (isset ($val) && $val != "") $val = htmlspecialchars ($val); else $val = " "; printf (" ", $val); } print (" "); } mysql_free_result ($result_id); print ("

<a href="">%s</a>
%s

"); mysql_close ($conn_id); ?>

In Recipe 18.8, I mentioned that placeholder techniques apply only to data values, not to identifiers such as column names. Our sort parameter is a column name, so it cannot be "sanitized" using placeholders or an encoding function. Instead, the script performs a rudimentary test to verify that the name contains only alphanumeric characters and underscores. This is a simple test that works for the majority of table names, though it may fail if you have tables with unusual names. The same kind of test applies also to database, index, column, and alias names.

Another approach to validating the column name is to run a SHOW COLUMNS query to find out which columns the table actually has. If the sort column is not one of them, it is invalid. The clicksort.php script shown here does not do that. However, the recipes distribution contains a Perl counterpart script, clicksort.pl, that does perform this kind of check. Have a look at it if you want more information.

The cells in the rows following the header row contain the data values from the database table, displayed as static text. Empty cells are displayed using   so that they display with the same border as nonempty cells (see Recipe 17.4).

Using the mysql Client Program

Writing MySQL-Based Programs

Record Selection Techniques

Working with Strings

Working with Dates and Times

Sorting Query Results

Generating Summaries

Modifying Tables with ALTER TABLE

Obtaining and Using Metadata

Importing and Exporting Data

Generating and Using Sequences

Using Multiple Tables

Statistical Techniques

Handling Duplicates

Performing Transactions

Introduction to MySQL on the Web

Incorporating Query Resultsinto Web Pages

Processing Web Input with MySQL

Using MySQL-Based Web Session Management

Appendix A. Obtaining MySQL Software

Appendix B. JSP and Tomcat Primer

Appendix C. References



MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2005
Pages: 412
Authors: Paul DuBois

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net