是否可以使用选择下拉列表对MySql结果进行排序?

时间:2014-04-19 15:26:08

标签: php html mysql

我是一个关于在线出版系统的项目,在这个网站上有用户。我已经在我的网站上获得了MySql结果,由于某种原因,结果是随机的。我想使用select,option标签对下拉列表列表对用户数据库结果进行排序...我应该使用什么才能使此功能正常工作? 这是我想要排序的代码:

    <form>
    <label>Sort By:</label>
        <select name="sort" id="sort" style="float: left;">
            <option value="ID">Id Number</option>
            <option value="name">Name A-Z</option>
            <option value="surname">Name Z-A</option>
            <option value="title">Academic Title</option>
            <option value="department">Departments</option>

        </select>
    </form>

1 个答案:

答案 0 :(得分:1)

试试这个

<html>
<head>
<script>
function sortResult(str)
{
if (str=="")
  {
  document.getElementById("result").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("result").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","results.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="sortby" onchange="sortResult(this.value)">
            <option value="ID">Id Number</option>
            <option value="name">Name A-Z</option>
            <option value="surname">Name Z-A</option>
            <option value="title">Academic Title</option>
            <option value="department">Departments</option>
</select>
</form>
<br>
<div id="result"><b>Results will be listed here.</b></div>

</body>
</html>

你的results.php

<?php
$q = $_GET['q'];

$con = mysqli_connect('localhost','username','password','my_db');
if (!$con)
  {
  die('Could not connect: ' . mysqli_error($con));
  }

mysqli_select_db($con,"database");
$sql="SELECT * FROM tablename ORDER BY ".$q;

$result = mysqli_query($con,$sql);

echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Title</th>
<th>Department</th>
</tr>";

while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" .$row['ID']. "</td>";
  echo "<td>" .$row['name']. "</td>";
  echo "<td>" .$row['surname'] ."</td>";
  echo "<td>" .$row['title']. "</td>";
  echo "<td>" .$row['department']. "</td>";
  echo "</tr>";
  }
echo "</table>";

mysqli_close($con);
?>