MYSQL不会是ORDER BY变量

时间:2013-07-28 00:09:21

标签: php mysql

我无法将此函数用于ORDER BY变量。如下图所示,它完美无缺。如果我将单词“cabin”更改为变量,即使是已经为此工作的相同变量,它也不起作用并返回下面列出的错误。

使用:

function makedropdown($connection, $table) {
        $result = mysqli_query($connection,"SELECT * FROM $table ORDER BY cabin ASC");
        if (!$result) {
            die ("Database query failed:" . mysqli_error());
        }
        echo "<select name='delcabin'>";
        While ($row=  mysqli_fetch_array($result)){
             echo "<option>" . $row[1] . "</option>";
        }
        echo "</select>";
}

不起作用:

$result = mysqli_query($connection,"SELECT * FROM $table ORDER BY $table ASC");

收到错误消息:

  

mysqli_error()只需要1个参数,0给定

提前致谢。

2 个答案:

答案 0 :(得分:1)

就个人而言,我会修改函数以接受第三个参数来按变量设置顺序。

function makedropdown($connection, $table,$OrderBy) {
        $result = mysqli_query($connection,"SELECT * FROM $table ORDER BY $OrderBy ASC");
        if (!$result) {
            die ("Database query failed:" . mysqli_error($connection));
        }
        echo "<select name='delcabin'>";
        While ($row=  mysqli_fetch_array($result)){
             echo "<option>" . $row[1] . "</option>";
        }
        echo "</select>";
}

然后分别通过以下方式调用它:

$Conn = new mysqli(); // This is a test database connection call, for example only. 
$Tablename = "TestTable"; // This is a valid table within the schema 
$ColumnName = "TestColumn"; // This is a valid column within the SQL Table 

    makedropdown($Conn,$TableName,$ColumnName);

这样,您可以避免查询:

$Table = "Cabin"; 

SELECT * FROM $Table ORDER BY $Table ASC
当回声时,将打印出来:

SELECT * FROM Cabin ORDER BY Cabin ASC

答案 1 :(得分:0)

这样做......

  $result = mysqli_query($connection,"SELECT * FROM $table ORDER BY '{$yourvariable}' ASC"); 

另外....确保您的变量是有效列,否则它将不起作用。

所以在这种情况下是$ table,是你的表名,也是一个有效的列名?