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
Related
To be clear, I need to search the table in database, specifically field called tags which is defined as text. Into the database, I am entering those 'tags' as a string and then I am exploding / dividing this string of 'tags' by explode() method into array in php. But for search of multiple 'tags' in form I need to enter multiple tags divided by SPACE and then by #.
Problem is that I do not know how to tell database to ignore order of entered tags and display all pictures which contains entered tags in search form ignoring the order of entered tags. Until now I was able to search only pictures where tags were in order.
I have tried to do it this way but it did not work
$search_string = $_POST['search'];
$exploded_search_string = explode(" ", $search_string);
$sql_search = "SELECT * FROM pictures
WHERE tags LIKE '%".$exploded_search_string."%'
ORDER BY ID_picture DESC";
I think you could do something like this
WHERE tags LIKE ’$exploded_search_string[0]%' OR tags LIKE '%$exploded_search_string[1]%'
OR
WHERE tags REGEXP '$exploded_search_string[0]| $exploded_search_string[1]'
You can loop the $exploded_search_string array to create the SQL statement like above and your select query should find all the tags found in DB.
Once you be able to get the results using the above statement, you could check FULL TEXT search for an optimized solution.
You don't say what database you're using. Assuming you're using MySQL you could take a look at full-text searching.
Also, you should consider using PDO so that you can use prepared statements to help prevent SQL injection attacks.
if your tags are identical to the ones in the db, use IN instead of LIKE
$sql_search = "SELECT * FROM pictures
WHERE tags IN ($exploded_search_string)
ORDER BY ID_picture DESC";
I have a list of customer in a database with a column name is postcode
At the moment my search runs the SQL
SELECT *
FROM customer
WHERE postcode LIKE '%".$_POST["search term"]."%'
Which works fine but if a row in the databse has the postcode of (SS1 1AB) and someone types in (SS11AB) how can I make it find the correct row?
Basically I want to be Able to search every single combination etc
Only way you could probably do is to with either a regex or white space replacement.
PHP: $term = str_replace(' ', '', $_POST["search term"]);
Query: Select * from customer where REPLACE(postcode, ' ', '') LIKE '%".$term."%'
Having said that however, you'd be far better off formatting the data on insert, because as your table grows, that lookup will become more and more expensive to run. One of my pet hates is websites that use a post code as authentication or verification data, then force you to use a particular notation. I've seen people hypenate the space in their post code before too, so you should always normalise the format before inserting it, or enforce a format (i prefer the former option, but the latter is easier).
Also your query is vulnerable to injection exploits. But thats another topic
Besides the SQL injection, Which you should sort out.
The column should be SS11AB, then query on str_replace(" ", "", $_POST['search term'])
you can make your column look like that by
update customer set postcode = replace(postcode, " " , "")
That will remove all spaces in the column, Then you just need to query without the space with the function above
Mysql allows regular expression matches which would be one way. What I would do though is standardize on a single correct representation in the database - and validate input against that. This would avoid SQL injection issues and make matching easier. It would also allow you to filter out typos when data is entered into the database.
i have a table called username which has for example John Doe and i want to get this value in a php action for $username! I use this
mysql_query("SELECT * FROM photos WHERE username = '$username'");
it works fine. Im using this for a searchfield to return different Users and their profile.
The question is, how can i search with eg only the first name John and he gives me John Doe back.
I dont want to create a first and last name!
Thanks Ted
SELECT * FROM photos WHERE username LIKE '%$username%';
With a word on security: If $username is the value of a search field in your site, you should escape the given search pattern correctly, not to get your database injected. This is simply done by the following code:
$escaped_username = mysql_real_escape_string($_REQUEST['username']);
mysql_query("SELECT * FROM photos WHERE username LIKE '%$escaped_username%'");
This will perform a secure search in your table, with the possibility of using just first or last name.
Legend: $_REQUEST['username'] is the value of your search form.
You can use LIKE for pattern matching,
SELECT * FROM photos WHERE username LIKE CONCAT('%','$username', '%')
but this will perform slow in large database because it will not use index causing to perform FULL TABLE SCAN.
$query = "SELECT * FROM photos WHERE username LIKE CONCAT('%',$username, '%')"
mysql_query($query);
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
You can use LIKE MySQL clause in the query
SELECT * FROM photos WHERE username LIKE '$username%'
You can use CONCAT Function to get Full name
SELECT CONCAT(First_name, ' ', Lastnale,)
FROM photos
WHERE username LIKE '$username%'
For example, if I search for 'cat' I get all the titles with the word 'cat' in it, such as 'cat in the hat'.
If I type in 'cat hat' I should get back 'cat in the hat', but the query returns empty, because its looking for exactly 'cat hat' and ignoring 'cat in the hat'.
I need some sort of select where it looks up all titles with any word I search for, then does that for the next word, etc... and then... I dont know, some sort of big AND thingy...
So far Im playing with somethign like:
$query = "SELECT title
FROM books
WHERE TITLE LIKE '%" . $search . "%' LIMIT 0,75;";
Probably need some sort of recursive function where it breaks the search input into an array of strings and does a search on each of those then merges them.
Ideas?
You are looking for MySQL Full-Text Search
$query = "SELECT title
FROM books
WHERE TITLE LIKE '%" . $search1 . "%' AND LIKE '%" . $search2 . "%' LIMIT 0,75;";
You need to add an AND clause for each search term. You could also add an OR if you wanted. They would give different results. OR would have a greater number of results and AND would of course be way more specific.
You should be able to do this with an array of inputs if it is simply querying against one field. If it's multiple fields, you'll have to do it using a map.
One thing I would like to point out is that this looks suspiciously like a target for SQL injection. Please be very wary when concatenating SQL queries together in a string. The final result must be escaped and / or parameterized to prevent users from running arbitrary SQL.
Answers:
Split the $search on normal symbols and white space and then build the query
Use MySql Full Text Search
Pitfalls:
Full SQL text search is the better option it will result in faster results. Also be aware that your current query is vulnerable to SQL Injection please use mysqli::real_escape_string to avoid this.
Thanks
My database has name records that occasionally contain apostrophes, such as Joe's Bar and I've just coded a query script in PHP that grabs that field and sticks it into a select statement with the usual $query = "SELECT address FROM restaurants WHERE name='$name'"; and the apostrophe in some of the restaurant names derails the Love Train.
How do I keep this from happening?
Snide answer - Use the same technique you used when you inserted them INTO the database via PHP.
Rebuttal - I was having the same problem then and cheated and entered the troublesome ones directly using PHPMyAdmin but this can't be ignored any longer.
Thank you for taking the time to answer this during the holidays.
You have to $name = mysql_real_escape_string($name); before that line.
You might also want to read up on SQL Injections, since your inputs are clearly unsanitized.
Have a look here
How can I use an apostrophe (') in a
query string?
mysql_real_escape_string
PHP mysql_real_escape_string