Mysql Search Box using LIKE - php

I created a search engine on my website where user can input whatever they like and show the result. Below is the code I use to get the result but it is not working because of the syntax error.
In my database I have 10 rows, each rows contain 4 columns(id, author, second_author, book_name). My goal is, if the user enter a name that is found in 'author', I want to retrieve that result, 'OR' if they enter a name that is found in book_name I want to retrieve that result and so on for the other columns..
I know the proper way to do this is by using LIKE Operator, but how about if you want to compare the keywords to several columns, what should you do?
I've tried this but was not working:
SELECT * FROM book_list WHERE author OR second_author OR book_name LIKE '%".$search_key."%'

It's just a syntax tweak:
SELECT * FROM book_list
WHERE author LIKE '%".$search_key."%'
OR second_author LIKE '%".$search_key."%'
OR book_name LIKE '%".$search_key."%'
Hope that helps

Your query has an error, you have to search on each column as
SELECT * FROM book_list WHERE author LIKE '%".$search_key."%' OR second_author LIKE '%".$search_key."%' OR book_name LIKE '%".$search_key."%'
I would also like you to be aware that you are at risk of sql injection, have a look here How can I prevent SQL injection in PHP?. You should use prepared statment to avoid any risk

Related

SQL update with multiple criteria

I know this is quite simple but I've been looking at this for awhile and can't seem to identify what the issue is. I want to update a row in a table using two criteria. When I use either criteria, the table updates fine but when I combine them, it doesn't work.
This is the query
$updatequery = "UPDATE query SET audio='$finalpath' WHERE content='$title' AND WHERE userid LIKE '%$regID%'";
An example of the reg id:
APA91bGHS59rrpM0sbX9PIYT3SzXs-W1yEtGa2xGMGJXi8O1vW2SrgN7koHDj2o6ZwKvkd3TxtzhktsiVtQNSYQRa4uNDF7Yy0VOf0BJfQOnJWMtN2WBQjmVDsuU-0GxmceNLd8SWqOM
An example of content :
Where can I find a car
You only need to use the where keyword once:
$updatequery =
"UPDATE query SET audio='$finalpath' WHERE content='$title' AND userid LIKE '%$regID%'";
# "WHERE" removed here ------------------------------------^
Mandatory comment:
Using string manipulation like this leaves your code vulnerable to SQL-injection attacks. You should really consider using prepared statements instead.
WHERE content='$title' AND userid LIKE '%$regID%'
Where is needed only once
You can have only one WHERE clause, so this is a syntax error:
WHERE content='$title' AND WHERE userid LIKE '%$regID%'
Combine the logic in a single clause:
WHERE content='$title' AND userid LIKE '%$regID%'
The WHERE clause essentially works like conditionals in any other language. You can build up as complex a tree of boolean conditions as you like, as long as the whole thing resolves down to a boolean then it's fine.
Your query is wrong.
Try this:
$updatequery = "UPDATE query SET audio='$finalpath' WHERE content='$title' AND userid LIKE '%$regID%'";
EDIT:
Where is needed only once.

Mysql query not finding first word

I'm building a simple search engine in PHP that retrieves animal names from a MySQL database when the user searches it.
Say I have the following table:
ID | Name
---------------
1 | Red panda
2 | Okapi
3 | Red fox
When the user inputs "panda" it returns the Red Panda row, when they input "red panda" it again returns the Red Panda row.
But when a user inputs "red" it returns nothing.
However searching "Okapi" does work.
For some reason searching the first word in a multiple made of multiple words doesn't return anything.
The query I'm using to find the data is the following:
"SELECT * FROM example_table WHERE Name LIKE '%%$search'"
If you need to find anything which contains what you're searching for then you should use the % wildcard both before and after your $search in the query.
Hence you should do:
$query = "SELECT * FROM example_table WHERE Name LIKE %$search%";
The way you're currently using will match only those values which have the $search at the end of it.
For instance:
ID | Name
---------------
1 | Red panda
2 | Okapi
3 | Red fox
4 | kaok // added for examples
matching %ka:
won't return anything because kaok and Okapi have something after the ka. With this query you're looking for everything that starts with your expression;
matching %ka%:
will return both kaok and Okapi. With this query you're looking for everything that contains your expression;
matching ka%:
will return only kaok. With this query you're looking for everything that ends with your expression.
Take a look at the MySQL Dev guide about pattern matching.
Of course, as pointed out by Elzo Valugi, in his answer you need to remember to sanitise your inputs to avoid SQL Injections.
You can use it like this:
"SELECT * FROM example_table WHERE Name LIKE '%".$search."%'";
You placed a wildcard at the begin of your like string, so you will find any names which end with the search term.
To search for all names which contain the search term add a wildcard at the end of the like string:
LIKE '%$search%'
It returns nothing because your SQL Query needs to be modified slightly:
Change this
"SELECT * FROM example_table WHERE Name LIKE '%%$search'"
to this:
"SELECT * FROM example_table WHERE Name LIKE '%$search%'"
By adding % on both sides of the searched string, your database will look for any column value that has that word inserted into it.
Let me know if that solved it for you or if there are any more issues!
try this
% wildcard should be like this
$query = "SELECT * FROM example_table WHERE Name LIKE '%$search%'";
A side note, do not aggregate the user input directly to an SQL query. This is totally unsafe practice and leads to SQL injection, in fact all examples shown here are bad practice. Use binding parameters to create your query using mysqli or PDO.
$search = "%". "your_search_term" . "%";
$sth = $dbh->prepare('SELECT *
FROM example_table
WHERE name like :search');
$sth->bindParam(':search', $search, PDO::PARAM_STR, 12);
$sth->execute();
It has been issue with select query.You have to change select query only.
select * from tbl_pets where name like "%'".$data."'%"
and real mysql query
select * from tbl_pets where name like "%red%"
You can take a look here.I have created schema from that you can also check.
http://sqlfiddle.com/#!9/c08b0/1

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

select defined string value with mysql query of a table

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%'

php mysql search

My code contain
SELECT * FROM newchap WHERE company LIKE '%$company%' OR Category LIKE '%$cat%'
It works perfectly however, when the field $company contain empty, it return all result in MYSQL.
How to prevent it?
SELECT *
FROM newchap
WHERE (company LIKE '%$company%' AND company != '') OR Category LIKE '%$cat%'
Since the % wildcard can be any combination of characters, if it's empty you're selecting any company at all; your query in that case is
SELECT * FROM newchap WHERE company LIKE '%%' OR Category LIKE '%$cat%'
You could add an AND condition into the SQL to filter out the case where the company is empty, or you could just check for that in PHP. If this is a common case that should be faster, since it will save you running a query at all.
Also — and this is very important — if there's any chance that $company or $cat could contain user input, you should be using a parameterized SQL query. otherwise you're creating a vulnerability for an SQL injection.

Categories