0

I have a problem with sorting some data in my page. Here is the snippet:

<form name=frm action="" method="post" style="display: inherit;">
    <label>
       Эрэмбэ:
       <select class="input-select" name="qryorder" onchange="document.frm.submit()">
          <option value="asc">Price ascending</option>
          <option value="desc">Price descending</option>
       </select>
    </label>
</form>

Here is the data i want to sort:

enter image description here

Code snippet:

 <?php
    if(isset($_POST['qryorder'])) {
        $sort = $_POST['qryorder'];
        sort_by_price($sort);
        // header('Location: product.php');
    }
?>

And my function:

  function sort_by_price($sort)
{
    global $conn;

    $sql = "select * from product order by price = '{$sort}'";
    $result = $conn->query($sql);

    $list = array();

    while ($row = $result->fetch_assoc()) {
        $list[] = $row;
    }
    return $list;
}

What i exactly want is i need to sort some data ordered by price ascending and descending.

5
  • what is data you want to sort? Please explain more your issue. Commented Sep 22, 2019 at 5:24
  • I edit my question i want to sort that datas as price ascending and descending with select option Commented Sep 22, 2019 at 5:32
  • Show us your php code, bcz that it the one which does this sorting by altering mysql query. In MySQL query you have to change order by clause. Commented Sep 22, 2019 at 5:44
  • @JitendraYadav i 've edited my question take a look. Commented Sep 22, 2019 at 5:48
  • You really shouldn't be doing the sorting this way. Your code is vulnerable to SQL injection. Use whitelist. stackoverflow.com/a/60496/1839439 Commented Sep 22, 2019 at 8:33

1 Answer 1

1

Don't use = operator in you order by clause.

Reference: Sorting Rows

$sql = "select * from product order by price $sort";

Updated Code: Price field in table was VARCHAR which was causing incorrect sorting, converted into BIGINT.

Sign up to request clarification or add additional context in comments.

4 Comments

Fatal error: Uncaught Error: Call to a member function fetch_assoc() on bool in G:\development\tgnm\includes\functions.php:334 Stack trace: #0 G:\development\tgnm\product.php(5): sort_by_price('desc') #1 {main} thrown in G:\development\tgnm\includes\functions.php on line 334
check my updated answer, I forget to remove curly braces.
ctrl + f5 and then try changing sorting from dropdown
i cannot loading my page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.