排序不适用于PHP SQL ORDER BY

时间:2015-11-28 18:35:49

标签: php mysql

您好我已经设法在每个单击时按列对表进行排序。 这是我的表:

<table class="table table-hover">
            <thead>
                <tr>
                    <th><a href="?sort=id">Game ID </a></th>
                    <th><a href="?sort=title">Game title </a></th>
                    <th><a href="?sort=developer">Developers </a></th>
                    <th><a href="?sort=release">Year of release </a></th>
                    <th><a href="?sort=stock">No. of items in stock </a></th>
                    <th><a href="?sort=price">Cost price </a></th>
                    <th>Options</th>
                </tr>
            </thead>

然后我根据所选列使用它来排序表。

if (isset($_GET['sort'])){
                  $sort = $_GET['sort'];
                  $query = "SELECT * FROM Games ORDER BY " . $sort . ";";
                  $result = mysqli_query($connection, $query);

(在此代码下面,我使用循环将数据插入表中)

除了我的“发行年份”列之外,所有内容都完美无缺,当我点击此表时会清空。

我不知道为什么会这样。

1 个答案:

答案 0 :(得分:3)

Releasereserved term。你需要将它封装在反引号中;或更改您的列名称。您正在采用的这种方法也可以让您进行SQL注入。

我添加了一个白色的术语$_GET['sort']列表,并将其与$_GET['sort']进行比较。粗略的未经测试的代码示例:

$valid_columns = array('id', 'title', 'release', 'developer', 'stock', 'price');
if (in_array($_GET['sort'], $valid_columns)) {
     $sort = $_GET['sort'];
     $query = "SELECT * FROM Games ORDER BY `" . $sort . "`;";
//execute query and valid stuff
} else {
     echo 'invalid column supplied
}

通过这种方式,您可以了解SQL中最终会发生什么;否则,用户可以添加任何可能导致挂起应用程序时出错的内容。