Crazy Horse
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:
Controller:
DB Query:
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}
})
Controller:
$data = [
'sort' => $_POST['sort']
];
$reminders = $this->Model->Sort($data);
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;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Cheers guys, most helpful.
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/