I have a script where I’m trying to match the droppable data I retrieved in the form of an ajax $.post request that contains a firstname, lastname, description and grade and match it with that of the same data in my database. In doing so I want to find the user and fetch them out in my query. I’m having trouble making an efficient query using LIKE and am unsure what other component to add to make this happen correctly
if (isset($_POST['data'])){
$data = $_POST['data'];
$query = mysql_query("SELECT * FROM `tempusers`
WHERE `firstname` LIKE '%" . $data . "%'
OR `lastname` LIKE '%" . $data . "%'
OR `description` LIKE '%" . $data . "%'
OR `grade` LIKE '%" . $data . "%'");
if (! $query){
echo'Database error: ' . mysql_error();
}
while ($row=mysql_fetch_assoc($query)) {
$description = $row['description'];
echo $description;
}
exit;
}
The problem is that I am not returning any results and instead getting the errors
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
andmysql_fetch_assoc() expects parameter 1 to be resource, boolean given.
I welcome any tips that I can implement and wouuld greatly appreciate it
The query’s syntax is valid, that means you have a single quote somewhere in your input data, causing the query to fail with the syntax error.
To solve that you can pass your
$datathroughmysql_real_escape_string()which will escape any quotes, and most importantly prevent SQL Injection.Even better than escaping would be to use a parameterised query with PDO or MySQLi.
As for optimisation, you can try REGEXP instead of multiple LIKE’s. Example here.