I was seeking help in getting jquery autocomplete implemented and someone mentioned that that following code is susceptible to sql injections. Being new to programming, I was unable to tell how/why.
Would someone be able to explain in more detail, and the specific steps to take to wall off the security risk?
Thanks
JS:
$( "#filter" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://rickymason.net/blurb/main/search/",
data: { term: $("#filter").val()},
dataType: "json",
type: "POST",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 2
});
Controller:
public function search()
{
$term = $this->input->post('term', TRUE);
$this->thread_model->autocomplete($term);
}
Model:
public function autocomplete($term)
{
$query = $this->db->query("SELECT tag
FROM filter_thread ft
INNER JOIN filter f
ON ft.filter_id = f.filter_id
WHERE f.tag LIKE '%".$term."%'
GROUP BY tag");
echo json_encode($query->result_array());
}
You’re using
$termunescaped in your query. A malicious user can submit a string like' OR 1=1; DROP DATABASE;--– and you certainly don’t want that. Use mysql_real_escape_string() or the MySQLi equivalent to sanitize strings before putting them into a query.