创建一个按钮,对MYSQL查询进行升序和降序排序

时间:2012-07-28 03:41:31

标签: php mysql javascript-events

我是学生编码员。 我想创建一个排序按钮,按下时,按升序排序MYSQL查询。然后再次按下时,它将按降序排序。是的,现在,它只是背靠背地显示升序和降序表。

形成此按钮逻辑的最佳方法是什么?

感谢。 P.L。

  <form name="Email Header" method="post" action="{$_SERVER['PHP_SELF']}">
    <button type="submit" name="id_sort" class="button" value="1">ID</button>
    <button type="submit" name="from_sort" class="button" value="1">FROM</button>
    <button type="submit" name="to_sort" class="button" value="1">TO</button>
    <button type="submit" name="subject_sort" class="button" value="1">SUBJECT</button>
    <button type="submit" name="date_sort" class="button" value="1">DATE</button>
 </form>


// SORT 

if( isset( $_POST['id_sort'] ) )
   if( $_POST['id_sort'] == 1 )
     id_ASC_sort();
     $_POST['id_sort'] = 0;

if ($_POST['id_sort'] == 0)
  if( isset( $_POST['id_sort'] ) )
     if( $_POST['id_sort'] == 1 ) 
        id_DESC_sort();


 // query
    $sql = "SELECT * FROM messages ORDER BY message_id DESC";
    $result = mysql_query( $sql );

2 个答案:

答案 0 :(得分:2)

检查你的第二个条件块。你有一个等号而不是一个双等号。这意味着你实际上设置变量而不是检查它的值,它始终计算为true。

答案 1 :(得分:0)

我在您的代码中更改了以下行: -

<form name="Email Header" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

并添加了一个按钮: -

<button type="submit" name="asc_sort" id="asc_sort" class="button" value="1">Sort</button>

和更改查询

if(isset($_POST['asc_sort']) && !empty($_POST['asc_sort']) && $_POST['asc_sort']==1)
{
     $sql = "SELECT * FROM messages ORDER BY message_id ASC";

}else{

    $sql = "SELECT * FROM messages ORDER BY message_id DESC";
}

echo $sql;

试试这个

<form name="Email Header" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<button type="submit" name="id_sort" class="button" value="1">ID</button>
<button type="submit" name="from_sort" class="button" value="1">FROM</button>
<button type="submit" name="to_sort" class="button" value="1">TO</button>
<button type="submit" name="subject_sort" class="button" value="1">SUBJECT</button>
<button type="submit" name="date_sort" class="button" value="1">DATE</button>
<button type="submit" name="asc_sort" id="asc_sort" class="button" value="1">Sort</button>