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%'
Related
I am trying to implement the most relevant search result for a website.
Below is how I want it to look like:
If someone types in "Beauty" it should first search if any account username has the handle "#beauty" and display that one first, then the rest of the accounts that match the criteria below:
Matching keyword
Keyword in handle or account name
Keyword in account's bio
The code I am currently using:
$searchset = mysqli_real_escape_string($conn, rtrim($_GET['search']));
$sql = "SELECT * FROM accounts WHERE username LIKE '%".$searchset."%' OR keywords LIKE '%".$searchset."%' OR bio LIKE '%".$searchset."%')";
I have been reading on methods using weighted search or mysql MATCH(), but I couldn't figure out the best code to achieve my required results.
A simple ORDER BY should do the job:
$sql = "SELECT * FROM accounts WHERE username LIKE '%".$searchset."%' OR keywords LIKE '%".$searchset."%' OR bio LIKE '%".$searchset."%') ORDER BY '$searchset' != username";
You should look into prepared statements, and I recommend using PDO instead of mysqli. The syntax is much more modern and there are many shortcuts and convenience methods available.
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'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
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
I was running a site I purchased that I thought was fairly unhackable. However, after having an attack, I found it was not. He informed me of the vulnerability, however my question is what user input could have been done to get all the users usernames like he did? Here is the code...
$un=$_GET['username'];
$q=$db->query("SELECT * FROM users WHERE login_name='$un' OR username='$un'");
I realize that this is highley hackable. Therefore, I changed the site over to prepared statements to prevent this from happening again. I just want to know what he could have entered to get all the users usernames.
Someone posted the script on github, you can find it here:
https://github.com/sat312/Mafia-Game-Script/blob/master/checkun.php
' OR 1=1;
In the URL:
/yourScript.php?username=%27%20OR%201%3D1%3B
The idea is that since data is mixed with the command, you can just finish the command with data.
You get $un from the user, so I can type anything I want and it'll get substituted into your query. It's called a SQL Injection attack.
Lets say $un = ' OR 1 = 1;-- then your query becomes:
SELECT * FROM users WHERE login_name='' OR 1 = 1;--' OR username='' OR 1 = 1;--'
What will happen? this gets executed:
SELECT * FROM users WHERE login_name='' OR 1 = 1;
This will return every row in the table.
He may have used the GROUP_CONCAT statement in MySql which basically groups a column in multiple rows into a single row (see Can I concatenate multiple MySQL rows into one field? for more information). He may have terminated the original SQL statement or UNIONED it with his own and added a LIMIT and ORDER BY to ensure his result got returned and commented out the remained of the original statement.
This is one possibility, but there are probably a few others.