Searching database by string exploded into array - php

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";

Related

select from a select statement in php & mySQL

I am trying to add filters to a DB search. I have a search that takes some text and tries to find items with that text in the title. I also have a price range filter. That code is below and works just fine
$sql = "SELECT * FROM items where title LIKE '%". $title ."%' AND price > '". $price1 ."' AND price < '".$price2."' Limit 70";
Now I am trying to more and more filters. Is there a select from the above code's output? I don't want to just keep making a longer SELECT statement with tons of if statements. I'd prefer to take the output of the previous select and refine that with another select. Is this possible?
EDIT 1 Context:
Users are the ones entering the information. This is for searching the items on my site.
There's no other useful way than adding lots of different conditions to your WHERE cause, if you use plain SQL. It is possible to use several nasted SELECT statements in your query, but this makes your code neither any more readable nor faster.
A more elegant solution is the usage of query objects or another form of object-oriented query abstraction (e.g. ZendDB).
You can use some of the mysql string functions like INSTR(), MATCH which will make your life a little easy and also help the readability of the code.
You can also use REGEXP and NOT REGEXP for pattern matching . The list of string functions are here.

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

Php and mysql wildcard operator when searching a database

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.

Im writing a library search program for my personal library, having trouble with a select with multiple words

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

PHP MySQL input HTML tags

I have a PHP MySQL database which I will be storing all my information in. I have a text field on a HTML page that the user can add data to and then on submit a MySQL query inserts this information into a database. Pretty standard stuff.
However, I am now in a position where I can attach a TinyMCE or FCKEditor onto my text field (now a text area). My question is: How do I get this information into the database now, taking into account that the tags will affect the MySQL query, and stripping any tags would impair the display of said information on another page?
I know about strip_tags and similar PHP features but my problem isn't going to be with the PHP it's going to be with the database input with MySQL, any " or ' or ; will break the query and removing these tags before input would remove any format enhancements the user has made.
I am under the assumption also, that if I use mysql_real_escape_string I would need to strip the slashes before I display the data - and this would take all the slashes out of the close tags as well: , etc.
You need to escape the value before you insert it in your SQL statement. If you use the mysql extension, you use the mysql_real_escape_string to do this:
$text = mysql_real_escape_string($_POST['text']);
It escapes characters such as quotation marks, so you can safely insert the value in database.
Look at this:
http://php.net/manual/en/function.mysql-real-escape-string.php
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));

Categories