PHP MYSQLi按多个字段排序/排序

时间:2017-05-21 11:33:38

标签: php mysqli

我试图通过asc / desc命令中的tableheader进行排序/排序工作,但是我的asc命令仍然存在。

我知道代码可能存在一些安全问题,但我希望现在能够正常工作并在以后加强它。

<?php
$con = mysqli_connect($dbhost,$dbuser,$dbpass);
mysqli_select_db($con,$database) or die ("Unable to select database");

// menu creation
echo "<div class=\"menu\"><ul>";
echo "<li><a href=\"index.php?name=\"> All </a></li>";

for ($i="A"; $i != "AA"; $i++) 
echo "<li><a href=\"index.php?name=$i\"> $i </a></li>";

if(isset($_REQUEST['name'])){
 $i= strip_tags($_REQUEST['name']);
}

//table sorting

$orderBy = array('name', 'date', 'genre', 'art', 'topic', 'version');
$order = 'name';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
    $order = $_GET['orderBy'];
}

$sortBy = array('asc', 'desc');
$sort = 0;
if (isset($_GET['sort']) && in_array($_GET['sort'], array_keys($sortBy))) {
    $sort = $_GET['sort'];
}

$data = mysqli_query($con, 'SELECT * FROM games ORDER BY ' . $order . ' ' . $sort) or die (mysqli_error($con));

echo "</ul></div>";

// table result

echo"<div class='table'><table><thead><tr>
<th><a href='?orderBy=name&sort=0'>Name</a></th>
<th><a href='?orderBy=date&sort=0'>Date</a></th>
<th><a href='?orderBy=genre&sort=0'>Genre</a></th>
<th><a href='?orderBy=art&sort=0'>Art</a></th>
<th><a href='?orderBy=version&sort=0'>Version</a></th>
</thead></tr><tbody>";

while($row = mysqli_fetch_array($data)){
  echo "<tr>";
  echo "<td>" . $row['name'] . "</td>";
  echo "<td>" . $row['date'] . "</td>";
  echo "<td>" . $row['genre'] . "</td>";
  echo "<td>" . $row['art'] . "</td>";
  echo "<td>" . $row['version'] . "</td>";
  echo "</tr>";
}
echo "</tbody></table></div>";

mysqli_close($con);

1 个答案:

答案 0 :(得分:1)

看起来你已经设置好了,你的URL排序是0或1.然后你将sort设置为等于0或1,而不是ASC或DESC,所以MySQL不理解。试试这个

$sortBy = array('asc', 'desc');
$sort = 'asc';
if (isset($_GET['sort']) && in_array($_GET['sort'], array_keys($sortBy))) {
    $sort = $sortBy[$_GET['sort']];
}

编辑:

您的表格标题将始终按ASC排序,无论您点击它多少次,因为它未设置为更改:

$data = mysqli_query($con, 'SELECT * FROM games ORDER BY ' . $order . ' ' . $sort) or die (mysqli_error($con));

echo "</ul></div>";

// table result

$sort = ($sort == 'desc' ? 1 : 0);

?>

  <div class='table'><table><thead><tr>
  <th><a href='?orderBy=name&sort=<?= ($order == 'name' ? ($sort == 0 ? 1 : 0) : 0); ?>'>Name</a></th>
  <th><a href='?orderBy=date&sort=<?= ($order == 'date' ? ($sort == 0 ? 1 : 0) : 0); ?>'>Date</a></th>
  <th><a href='?orderBy=genre&sort=<?= ($order == 'genre' ? ($sort == 0 ? 1 : 0) : 0); ?>'>Genre</a></th>
  <th><a href='?orderBy=art&sort=<?= ($order == 'art' ? ($sort == 0 ? 1 : 0) : 0); ?>'>Art</a></th>
  <th><a href='?orderBy=version&sort=<?= ($order == 'version' ? ($sort == 0 ? 1 : 0) : 0); ?>'>Version</a></th>
</thead></tr><tbody>

<?php
相关问题