有一个错误导致它不能在ASC / DESC之间翻转,我90%肯定它在这几行之内。我想我需要有一个"第一个"循环将"保存" $ sort所以它稍后翻转。但是当我这样做时会导致数组错误。
SQL很可能是正确的...... 我并不担心SQL注入/ PDO /安全性,因为我稍后会添加该代码。
完整链接:https://solenoidal-slate.000webhostapp.com/
if(isset($_GET['sort'])){
$sort = $_GET['sort'];
} else {
$sort='ASC';
}
$sort == 'DESC' ? $sort ='ASC': $sort='DESC';
$query = "SELECT * FROM employees ORDER BY $order $sort";
$results = mysqli_query($con, $query); ?>
<th><a class="column_sort" id="id" href='?order=id&sort=$sort'>ID<span class="glyphicon glyphicon-sort-by-alphabet"></span></a></th>
以上这一行是&#34;获取&#34; $ sort变量。
编辑:为节省时间,$ order不是问题。每个列名称都按列成功排序。
if(isset($_GET['order'])){
$order = $_GET['order'];
} else {
$order = 'id';
}
答案 0 :(得分:1)
执行:
$sort = ($sort == 'DESC') ? 'ASC': 'DESC';
并且只写一个&#34;&amp;&#34;在查询字符串键/值对之间:
<a ... href="?order=id&sort=$sort">
并在&#34; href&#34;中正确应用php代码。否则,您也会将$sort
作为HTML代码。
所以,我会这样做,例如:
<?php
$order = isset($_GET['order']) ? $_GET['order'] : 'id';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'ASC';
$sort = ($sort == 'ASC') ? 'DESC': 'ASC';
$query = "SELECT * FROM employees ORDER BY $order $sort";
$results = mysqli_query($con, $query); ?>
//....
?>
<th>
<a class="column_sort" id="id" href="?order=id&sort=<?php echo $sort; ?>">
ID<span class="glyphicon glyphicon-sort-by-alphabet"></span>
</a>
</th>
或者你可以直接使用它:
<?php
//...
$sort = ((isset($_GET['sort']) ? $_GET['sort'] : 'ASC') == 'ASC') ? 'DESC' : 'ASC';
$query = "SELECT * FROM employees ORDER BY $order $sort";
//...
答案 1 :(得分:0)
你的最终代码是这样的:
if (isset($_GET['order'])) { // Check $_GET['order'] is in the predefined array
$order = $_GET['order'];
} else {
$order = 'id';
}
if(isset($_GET['sort'])) { // Preferably you can check this also in_array($_GET['sort'], ['ASC', DESC])
$sort = $_GET['sort'];
} else {
$sort = 'ASC';
}
$query = "SELECT * FROM employees ORDER BY $order $sort";
$results = mysqli_query($con, $query);
您的链接需要更改,
应该是http://solenoidal-slate.000webhostapp.com/?order=id&sort=DESC或ASC,并从链接中删除一个&
现在就是这样:https://solenoidal-slate.000webhostapp.com/?order=id&&sort=$sort