Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

How to sort ASC or DESC with passed in value instead of hardcoded SQL query value

I am trying to pass in the value ASC to the database for a query but the error I get is:

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ASC''
Here is what I am sending via Ajax for testing:

var sort = 'ASC';
$.ajax({
        url: url + '/Admin/test',
        type: 'POST',
        dataType: 'json',
        data: {sort: sort}
    })

Open in new window


Controller:

    $data = [

        'sort' => $_POST['sort']
    ];

$reminders = $this->Model->Sort($data);

Open in new window


DB Query:

$this->db->query("SELECT fields
FROM tables
ORDER BY name :sort ");
$this->db->bind(":sort", $data['sort']);
$results = $this->db->resultSet();
return $results;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi,

I rarely sort  order directly into the MySQL
I do prefer to do on the page using Javascript, this way if I need to change it later I only need to change frontend JS code not the BD query...

I you display data inside a table that is very easy to do, specialy if you use Datatables https://datatables.net/
Avatar of Crazy Horse

ASKER

Cheers guys, most helpful.