Reputation: 14783
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
Upvotes: 1
Views: 578
Reputation: 178
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.
Upvotes: 2
Reputation: 3548
You can use CONCAT Function to get Full name
SELECT CONCAT(First_name, ' ', Lastnale,)
FROM photos
WHERE username LIKE '$username%'
Upvotes: 0
Reputation: 550
You can use LIKE
MySQL clause in the query
SELECT * FROM photos WHERE username LIKE '$username%'
Upvotes: 1
Reputation: 263723
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.
Upvotes: 1