0

所以我试图根据单击的提交按钮对 SQL 查询进行排序

我的排序选项:

echo "<form method='post' action adminview.php'>"
    ."<input type='submit' name='sort' value='Sort by Attempt ID'/><br />"
    ."<input type='submit' name='sort' value='Sort by Student ID'/><br />"
    ."<input type='submit' name='sort' value='Sort by lowest Score'/><br />"
    ."<input type='submit' name='sort' value='Sort by highest Score'/><br />"
    ."</form>";

当页面重新加载时,这里是检查单击哪个按钮的代码

switch($_POST['sort'])
{
    case "Sort by Attempt ID":
        $sortby = "attempt_id";
        break;
    case "Sort by Student ID":
        $sortby = "student_id";
        break;
    case "Sort by lowest Score":
        $sortby = "score";
        break;
    case "Sort by highest Score":
        $sortby = "score desc";
        break;
}

我的问题是,当页面重新加载时,它说排序是未定义的。

如果你好奇这里是 SQL 语句

$sqlstring = "select * from quizattempts order by '$sortby'";
4

3 回答 3

2

单引号阻止$sortby被评估。只需删除它们:

$sqlstring = "select * from quizattempts order by $sortby";
于 2013-11-03T05:40:02.760 回答
0

你能试试这个吗

<?php 
      echo "<form method='post' action='adminview.php'>"
           ."<input type='submit' name='sort' value='Sort by Attempt ID'/><br />"
           ."<input type='submit' name='sort' value='Sort by Student ID'/><br />"
           ."<input type='submit' name='sort' value='Sort by lowest Score'/><br />"
           ."<input type='submit' name='sort' value='Sort by highest Score'/><br />"
          ."</form>";

        if(isset($_POST['sort'])){

            switch($_POST['sort'])
            {
                case "Sort by Attempt ID":
                    $sortby = "attempt_id";
                    break;
                case "Sort by Student ID":
                    $sortby = "student_id";
                    break;
                case "Sort by lowest Score":
                    $sortby = "score";
                    break;
                case "Sort by highest Score":
                    $sortby = "score desc";
                    break;
            }

            $OrderBy = "order by $sortby ";
        }

         echo $sqlstring = "select * from quizattempts $OrderBy";
于 2013-11-03T06:22:37.233 回答
0

而不是单引号('),您需要使用重音(`)。在这种情况下,您可能不需要它,因为可以确定属性是单个单词。但是当你不确定属性是多个词还是单个词时,你应该总是使用重音

句法

select * from tab_name order by `attribute name` [ordering=asc/desc];

所以使用以下内容:

$ordering="asc";
switch($_POST['sort'])
{
    case "Sort by Attempt ID":
        $sortby = "attempt_id";
        break;
    case "Sort by Student ID":
        $sortby = "student_id";
        break;
    case "Sort by lowest Score":
        $sortby = "score";
        break;
    case "Sort by highest Score":
        $sortby = "score";
        $ordering="desc";
        break;
}
$sqlstring = "select * from quizattempts order by `$sortby` $ordering";

在这里,我在一个单独的变量中指定了排序,以防止其产生歧义。

于 2013-11-03T06:52:41.117 回答