PHP升序/降序不工作


PHP Order by Ascending/Descending not working

我正在设计一个简单的任务列表,但是我遇到了一个小问题。我希望能够通过单击表单按钮从数据库中订购项目,但它不工作。

这是在升序和降序之间排序的代码。

$type='ASC';
if(isset($_POST['sort'])) {
    if ($type == 'DESC') {
         $type = 'ASC';  
    }
}elseif($type == 'ASC') {
    $type='DESC';  
}

从DB获取结果的查询:

$sql = 'SELECT * FROM customers ORDER BY id '. $type;

(编辑:按钮是在表单标签与post方法)表单按钮:

<form method="post"><button type="submit" name="sort" id="asc"></button></form>

这(在我看来)应该能够工作,但它没有。有人愿意帮我找出问题所在吗?

如果要使用form,则需要将值保存到input type="hidden"。

<?php
 $type = $_POST["sortvalue"];
 if(!$type) {
     $type = "ASC";
 }
 if(isset($_POST['sort'])) {
     if ($type == 'DESC') {
         $type = "ASC";
     }elseif($type == 'ASC') {
         $type = "DESC";
     }
 }
$sql = 'SELECT * FROM customers ORDER BY id '. $type;
?>
<form method="POST">
<button type="submit" name="sort" value="sort">Sort</button>
<input type="hidden" name="sortvalue" value="<?php echo $type; ?>">
</FORM>

希望这对你有用。: D

或者您可以使用AJAX

$("body").on("click", "#asc", function(e) {
 e.preventDefault();
 sort();
});
function sort() {
  var order = find("table#sort_order").val();
  $.ajax({
    url: 'process.php',
    type: 'POST',
    data: order,
    dataType: 'json',
    success: function(data) {
       // change sort order using data
    }, // End of success function of ajax form
    error: function(xhr, status, errorThrown) {
      console.log("Error: " + errorThrown);
      console.log("Status: " + status);
      console.dir(xhr);
    },
  }); // End of ajax call 
}