I'm currently changing all my mysql code to pdo to make it injection proof, but I'm farely new to both. Now I got a problem I can't wrap my head around. I try to populate autocomplete for an input-field through ajax using the following code:
ajax
$('#input').autocomplete({
source: function (request, response) {
$.ajax({
url: 'fc_autocomplete.php',
type: 'POST',
data: {
term: request.term,
column: searchColumn,
table: searchTable
},
dataType: 'json',
success: function (data) {
response(data);
},
error: function (response) {
alert('failed task');
}
});
},
minLength: 0,
autoFocus: true,
select: function (event, ui) {
value = ui.item.value;
$('#input').val(value);
$(this).blur();
},
close: function (event, ui) {
if ($('#input').val()) {
$('#input').val(value);
};
}
}).focus(function () {
$(this).data("uiAutocomplete").search($(this).val());
});
php/pdo
include_once('connect-db.php');
$term = trim($_REQUEST['term']);
//$term = str_replace('*', '\%', $term);
//$term = "$term%"; => First try
$column = $_REQUEST['column'];
$tb = $_REQUEST['table'];
$column2 = $column;
$stmt = $conn->prepare('SELECT '.$column.' FROM '.$tb.' WHERE :column LIKE :term ORDER BY :column2 ASC LIMIT 50');
$stmt->bindValue(':column', $column);
$stmt->bindValue(':term', $term."%");
$stmt->bindValue(':column2', $column2);
$stmt->execute();
//$stmt->execute(array(":column" => $column, ":term" => $term, ":column2" => $column2)); => First try
$response = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$response[] = $row[$column];
};
echo json_encode($response);
The commented out two commands were my first try. The code works perfectly as long as the input is empty (It shows all rows of the db. But as soon as I start typing, the list disappears completely (as if there aren't any results found). As you can see, I want it to search instead of the pure $term, for the $term with the % wildcard at the end. Why doesn't this work, though?
Also, preferably when the user enters a "*" somewhere in the term, I would like it to be switched into a "%" so that he can also find results not knowing the exact name. Is this even possible with prepared statements? Or does that work with the first commented out line?
Thanks for everyone's help.