这更像是一个查询而不是一个问题.我想为我的mysql数据库结果创建动态排序.我目前用查询输出结果.我想创建一个2链接,它将按所选链接对结果进行排序,再次单击并链接ASC或DSEC结果.
我一直在寻找,但无法找到正确的方法来做这件事.
我甚至下载了一个框架,看看这是如何完成的,但没有成功.
示例如下:
TITLE TOTAL
这听起来很简单,我无法在网上找到动态的例子.
其他任何人发现谷歌提供更多的结果到过时和论坛比实际有用的页面?
即使你按去年和相关性排序.希望有人能给我一些建议,谢谢
最佳答案
// build the basis for the query
$sql = '
SELECT
`id`,
`title`,
`total`
FROM
`my_table`
';
// check for sort field
$sort_by = isset($_GET['s']) ? $_GET['s'] : false;
// validate the sort field (avoid Bobby Tables!) and provide default
switch ($sort_by) {
case 'title':
case 'id':
case 'total':
break;
default:
$sort_by = 'id';
}
$sql .= ' ORDER BY '.$sort_by.' ';
// get the direction, or use the default
$direction = isset($_GET['d']) ? $_GET['d'] : false;
if ($direction != 'ASC' && $direction != 'DESC')
$direction = 'DESC';
$sql .= $direction;
// execute query, get results
$res = mysql_query($sql);
$results = array();
if ($res) {
while ($r = mysql_fetch_assoc($res)) {
$results[] = $r;
}
}
// used in table heading to indicate sort direciton
$sort_arrow = ($direction == 'ASC' ? '' : '
');
// used to build urls to reverse the current sort direction
$reverse_direction = ($direction == 'DESC' ? 'ASC' : 'DESC');
?>
if (count($results) > 0) {
foreach ($results as $r) {
print '
';print '
'.$r['id'].'';print '
'.$r['title'].'';print '
'.$r['total'].'';print '
';}
} else {
print '
No results found';}
?>