# [SOLVED] sorting button in php



## rsage (Nov 23, 2014)

hello. i want to know, how to make sorting button? any advice or tutorial... i am trying to make a button that when we click, it will sort the table. example it can sort by name, or id, or class... can it sort in same page or we need to link it to another page to display the sorting?
this example my table








right now what i have for my page is this.. i cant make the sort button.


----------



## DDAoN (Mar 19, 2011)

*Re: sorting button in php*

Well, you can sort the table dynamically using jQuery (check out tablesorter) or you can do it via the server. You would basically have to define the sort order of the query via the $_POST of the sort by dropdown.

...

Yeah, I know, it makes less sense when you give it some time to sink in, so let me try giving you an example. I through this together, real quick, using mysqli:

```
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Untitled Document</title>
 </head>

 <body><?php
 $con = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

 if(mysqli_connect_errno()) {
  echo 'Failed to connect to MySQL:<br />' . mysqli_connect_error();
 }

 $sortBy = (isset($_POST['sortBy']) ? $_POST['sortBy'] : NULL);
 $sql = 'SELECT * FROM personal_info';
 if($sortBy != NULL) {
  $sql .= ' ORDER BY ' . $sortBy;
 }
 $result = mysqli_query($con, $sql) or die(mysqli_error());
 if(mysqli_num_rows($result) > 0) {
  echo '
  <table>
   <tr>
    <th>ID</th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>SSN</th>
   </tr>';
  while($row = mysqli_fetch_array($result)) {
   echo '
   <tr>
    <td>' . $row['id'] . '</td>
    <td>' . $row['fname'] . '</td>
    <td>' . $row['lname'] . '</td>
    <td>' . $row['ssn'] . '</td>
   </tr>';
  }
  echo '
  </table>';
 }
?>

  <form>
   <select name="sortBy">
    <option value="id">ID</option>
    <option value="fname">First Name</option>
    <option value="lname">Last Name</option>
    <option value="ssn">SSN</option>
   </select>
   <button type="submit" formaction="?" formmethod="post">Submit</button>
  </form>
 </body>
</html>
```
This example has been tested to work. Yes, using the username "my_user", password "my_password", and database "my_db". What can I say? I felt like being stupid. ^^'

So, to explain what is happening:
Page initially loads
Tests database connection, if failed, end
Defined $sortBy PHP variable by whether $_POST isset()
Build $sql PHP variable
If $sortBy PHP variable != NULL, add ORDER BY clause to $sql PHP variable
Add proper query closure to $sql PHP variable
Query the database using $sql PHP variable and store results in $result PHP variable
If there were more than 0 results in $result PHP variable
Echo table header
While the is still an entry in the $result PHP variable, set it as the $row PHP variable and echo it's values to the table
Echo the proper table closure

Print form with dropdown named "sortBy" with options valued to the column name of the table being queried and a method of "POST"

Well, that doesn't explain much, well, I don't think it does, but then I read code for the explanation of what it does (not the comments). ^^'

The key to this is that it uses the name of the dropdown as the name of the $_POST variable. If the variable isn't set (like when the page is loaded with submitting the form) it'll default the value to NULL, which causes the PHP to not add an ORDER BY clause to the query. With the $_POST variable set, it'll add an ORDER BY clause to the query using the selected value of the form when it was submitted.

I hope this helps.


----------



## DDAoN (Mar 19, 2011)

*Re: sorting button in php*

Just occurred to me that it may also be helpful to see my database in relation to the example. ^^'


```
CREATE TABLE IF NOT EXISTS `personal_info` (`id` int(11) NOT NULL, `fname` varchar(50) NOT NULL, `lname` varchar(50) NOT NULL, `ssn` int(9) NOT NULL ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7;
INSERT INTO `personal_info` (`id`, `fname`, `lname`, `ssn`) VALUES (1, 'John', 'Jamerson', 654864654), (2, 'Jane', 'Jacobson', 984351845), (3, 'Jacob', 'Jeffries', 428661845), (4, 'Jason', 'Jarome', 157316420), (5, 'Jeffrey', 'Johanson', 864735421), (6, 'Jaquan', 'Jones', 664108343);
ALTER TABLE `personal_info` ADD PRIMARY KEY (`id`);
ALTER TABLE `personal_info`MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;
```
As exported from phpMyAdmin.


----------

