简体   繁体   中英

How to change the sql order value with select option using php and jquery

I need to change the ORDER value of an sql based on the chosen select option I have an action.php where I fetch the values from the DB. I want to put a sort select option where the loop fetch values order can be change based on the selected option.

action.php

if (isset($_POST["fetchValue"])) {  

echo '
 form name="sort" id="sort" action="" method="post">
 <div class="form-group">
     <label for="sort_item">Sort by: </label>
     <select name="sort_item" id="sort_item" class="form-control">
     <option value="age">Date of birth</option>
     <option value="last_name">Last Name</option>
     </select>
 </div>
 </form>';

 $fieldNameMapping = array(
        'age'     => 'dob',
        'last_name' => 'user_lastname');

$sql = "SELECT * FROM test_field_tb tf
        INNER JOIN users u ON tf.user_id = u.user_id
        WHERE tf.user_id = 5
        ORDER BY '".$fieldNameMapping[$_POST['sort_item']]."' "; // need to change that value base on the selected option

$run_query = $conn->query($sql);

while ($row = $run_query->fetch(PDO::FETCH_ASSOC)) {
...
 }

JQuery - js file

$(document).ready(function() {
$("#sort_item").change(function() {
    //get the selected value
    var selectedValue = this.value;

    //make the ajax call
    $.ajax({
        url: 'action.php',
        type: 'POST',
        data: {sort_item : selectedValue},
        success: function(data) {
            //how to i change the sql value here
        }
    });
});


function getFetch(){
    $.ajax({
        url :   "action.php",
        method: "POST",
        data    :   {fetchValue:1},
        success :   function(data){
            $("#get_display").html(data);
        }
    })
}

});

display.php

<div id="get_display"></div>

Getting error: Undefined index: sort_display $fieldNameMapping[$_POST['sort_item']]

The ORDER BY needs to be added conditionally

$sql = 'SELECT * FROM test_field_tb tf
        INNER JOIN users u ON tf.user_id = u.user_id
        WHERE tf.user_id = 5 ';
if (!empty($_POST['sort_item']))
        $sql .= "ORDER BY '".$fieldNameMapping[$_POST['sort_item']]."' ";

And in the success handler for the ajax call, populate the box like this:

success: function(data) {
        $('#get_display').html(data);
    }

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