Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem with jquery autocomplete and mySql

search.php

$text = $mysqli->$_POST['term'];
$query = "SELECT name FROM males WHERE name LIKE '%" . $text . "%' ORDER BY name ASC";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
    if (!$first) { $json .=  ','; } else { $first = false; }
    $json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;

index.php

1) HTML

<body>
Text: <input type="text" id="autocomplete" />
</body>

2) jQuery

    $( "#autocomplete" ).autocomplete({
        source: function(request, response) {
            $.ajax({ url: "http://localhost/testing/auto/search.php",
            data: { term: $("#autocomplete").val()},
            dataType: "json",
            type: "POST",
            success: function(data){
                response(data);
            }
        });
    },
    minLength: 2
    });

When I type 2 letters, it gives me all the names in my database even if these two letters do not match any of the names.

How does that happen and how do I fix it?

like image 803
Swell Avatar asked Feb 13 '26 05:02

Swell


2 Answers

Looks like my comment worked as an answer, hence this answer.

What does $mysqli->$_POST['term'] do? I think you should have $text = $_POST['term'];. This should work.

like image 118
Rakesh Sankar Avatar answered Feb 14 '26 19:02

Rakesh Sankar


Change the PHP to

$text = $_POST['term'];

$query = "SELECT name FROM males WHERE name LIKE '%" . $mysqli->real_escape_string($text) . "%' ORDER BY name ASC";
$result = $mysqli->query($query);

echo json_encode($result->fetch_all(MYSQLI_ASSOC));

You forgot to escape the input to prevent SQL injections. Additionally, use @mu's answer to fix your front-end code.

like image 41
Znarkus Avatar answered Feb 14 '26 19:02

Znarkus