有没有更好的方法来进行排序选项?

时间:2017-02-12 00:59:11

标签: php mysql sorting sql-order-by

所以,我正在尝试制作可以对数据库中的结果进行排序的选项。我找到了一种方法,但我不确定它是最好的。

if(!isset($_GET['sort']) || $_GET['sort'] == 0) {
    $userquery = $DBH->query("SELECT users.id, users.username, users.name, users.joined, users.usergroup, user_groups.group_title FROM users INNER JOIN user_groups ON users.usergroup = user_groups.id ORDER BY users.id ASC");
    $userquery->setFetchMode(PDO::FETCH_OBJ);
} else {
    if($_GET['sort'] == 1) {
        $userquery = $DBH->query("SELECT users.id, users.username, users.name, users.joined, users.usergroup, user_groups.group_title FROM users INNER JOIN user_groups ON users.usergroup = user_groups.id ORDER BY users.username ASC");
        $userquery->setFetchMode(PDO::FETCH_OBJ);
    } else if($_GET['sort'] == 2) {
        $userquery = $DBH->query("SELECT users.id, users.username, users.name, users.joined, users.usergroup, user_groups.group_title FROM users INNER JOIN user_groups ON users.usergroup = user_groups.id ORDER BY users.name ASC");
        $userquery->setFetchMode(PDO::FETCH_OBJ);
    } else if($_GET['sort'] == 3) {
        $userquery = $DBH->query("SELECT users.id, users.username, users.name, users.joined, users.usergroup, user_groups.group_title FROM users INNER JOIN user_groups ON users.usergroup = user_groups.id ORDER BY user_groups.group_name ASC");
        $userquery->setFetchMode(PDO::FETCH_OBJ);
    }
}

有没有更好的方法呢?

1 个答案:

答案 0 :(得分:0)

无需一遍又一遍地重复查询的不变部分。只需将其放入变量中,并根据条件将ORDER BY子句附加到该字符串。然后使用字符串作为查询参数。

$querystring = "SELECT users.id, users.username, users.name, users.joined, users.usergroup, user_groups.group_title FROM users INNER JOIN user_groups ON users.usergroup = user_groups.id ORDER BY ";
switch($_GET['sort']) {
  case 1:
  $querystring.= "users.username ASC";
    break;
  case 2:
  $querystring.= "users.name ASC";
    break;
  case 3:
  $querystring.= "user_groups.group_name ASC";
    break;
case 0:
default:
  $querystring.= "users.id ASC";
    break;
}

$userquery = $DBH->query($querystring);
$userquery->setFetchMode(PDO::FETCH_OBJ);