简体   繁体   English

PHP按升序/降序排序不起作用

[英]PHP Order by Ascending/Descending not working

I'm designing a simple task list, but I encountered a little problem. 我正在设计一个简单的任务列表,但是遇到了一个小问题。 I want to be able to order the items from the database by clicking on a form button, but it is not working. 我希望能够通过单击表单按钮从数据库中订购商品,但是它不起作用。

This is the code for ordering it between Ascending and Descending. 这是用于在升序和降序之间对其进行排序的代码。

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

The query for getting results from the DB: 从数据库获取结果的查询:

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

(EDIT: button is inside form tags with post method) and the form button: (编辑:按钮位于带有post方法的表单标签内)和表单按钮:

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

This (in my opinion) should be able to work, but it doesn't. (在我看来)这应该可以工作,但是没有。 anyone willing to help me find the problem? 有人愿意帮助我找到问题吗?

Or you can use AJAX . 或者,您可以使用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 
}

if you want to use form, you need to save the value to input type="hidden". 如果要使用表单,则需要保存该值以输入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>

hope this work for you.. :D 希望这项工作对您来说..:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM