2015-11-28 73 views
1

您好我设法按列排序时单击每个列。 这是我的表:排序不起作用的PHP SQL排序依据

<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); 

(在此之下的代码,我用一个循环来将数据插入到表)

所有完美的作品除了我的“上市年份”栏,当我点击这个桌子清空。

我不知道为什么会发生这种情况。

+0

如果以下答案解决了您的问题,请务必接受它,http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work。如果您有问题,请发帖。 – chris85

+0

将尝试它现在裸露在我身边,在此先感谢 – Gareth

回答

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中;否则用户可能会添加任何可能导致挂起应用程序错误的内容。

+0

在哪一点我需要封装我的专栏'释放'? – Gareth

+0

当它进入数据库时​​,它需要反引号。上面的代码应该处理'ORDER BY \'“。$ sort。”\''。所以它会是当它到达DB'SELECT * FROM Games ORDER BY \'release \';'时。 – chris85

+0

作品!感谢帮助哥们! – Gareth