user3544500 user3544500 - 7 months ago 32
PHP Question

Is it possible to sort MySql results with select dropdown list?

I'm a project about an online publication system and in this website there are users . I have already get MySql results on my website, for some reason, the results are random. I want to sort users database result with a drop down list using the select, option tag...what should I use to get this function works ?
Here is my code for what I want to sort by :

<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>

Answer

Try this

<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>

And your 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);
?>