简体   繁体   中英

php & mysql search query escape

I have a movie database website and I'm having a small issue with the search. Lets say that the movie name saved in the database is

Going Clear: Scientology and the Prison of Belief

As you can see there a : in the title.

When my users search for Going Clear Scientology and the Prison of Belief they get no results, same if the movie title has ' , here is my search query:

SELECT * FROM movie WHERE title LIKE '%$search%'

How can I fix that?

Keep two things in mind when trying to insert into the database using php.

First, when you are inserting into the database your data, say for example the movie name here "Going Clear: Scientology and the Prison of Belief", trim off the extra strings like : . This well help you later on.

Second, similar to the first one, when you are taking an input from the user sanitize it. There might be strings like ',$,\\,? etc which are not relevant. After you have done that you can go for a query search in the DB.

I guess your code here is okay.

select * from movie where title like 'Going%';

The above query works for me when I check it in my DB. See if your search variable is initializing properly.

You need to escapes special characters in a string for use in an SQL statement. Always store these type of value into database after escaping special character and also pass your search term into query after escaping special character.

For this you have to use

mysql_real_escape_string()

Eg:

 $search = "Going Clear: Scientology and the Prison of Belief";
 $search = mysql_real_escape_string($search);
 $query= "SELECT * FROM movie WHERE title LIKE '%$search%'";

You can read here

 http://php.net/manual/en/function.mysql-real-escape-string.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM