简体   繁体   中英

How to sort table values in ascending and descending with name value without using sort() function in PHP or ORDER BY in SQL?

I use the following code to get my resulted table, and I need to sort this table based on Clicking 'ascending' or 'descending' button respectively with my Name Value. How can I make a custom php function for this? Any help will be greatly appreciated.

<?php
require('config.php');
$sql_sel = "select * from contact";
$res_sel = mysql_query($sql_sel);
?>
<table><tr><td>Name </td><td>Email </td><td> Mobile</td><td>Web </td></tr>
<tr>
<?php
    while($row_sel = myqsl_fetch_array($res_sel)){
        $name = $row_sel['name'];
        $email = $row_sel['email'];
        $mobile $row_sel['mobile'];
        $web =$row_sel['web'];
        echo "<td>".$name."</td>";
        echo "<td>".$email."</td>";
        echo "<td>".$mobile."</td>";
        echo "<td>".$web."</td></tr>";

    }
?>
</table>

<input type="button" value="Ascending" onclick="ascending()">
<input type="button" value="Descending" onclick="descending()">

Where I getting table with values from database table as in the order of execution. My page having two buttons Ascending and Descending, while clicking on that, it results table values arranging in Ascending and Descending order based on name value. What should i code in 'ascending()' and 'descending()' to achieve this?i need this as a custom php function??

Let's say you are passing a value called "sort". It can be "dsc" for descending, and anything else (or not specified) for ascending.

First, start with parsing the value:

$sortMode = 'ASC';
if (array_key_exists('sort', $_REQUEST)) {
    if ($_REQUEST['sort'] == 'dsc') {
        $sortMode = 'DESC'
    }
}

Later on, when you create your query:

$sql_sel = "select * from contact order by name $sortMode";

This will cause the database to sort in the correct direction.

One important thing to note is that you should never ever ever pass user input (eg $_GET, $_POST, etc) directly into your SQL string so that you don't expose yourself to SQL injection attacks . Note that here we test the $_REQUEST parameter and set the actual PHP variable manually to avoid this.

In production applications, you should use parameter binding as much as possible (not relevant here since ASC/DESC is part of a statement, not a parameter).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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