supersize
supersize

Reputation: 14783

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

Upvotes: 1

Views: 578

Answers (5)

dieBeiden
dieBeiden

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

Sharad
Sharad

Reputation: 3548

You can use CONCAT Function to get Full name

  SELECT CONCAT(First_name, ' ', Lastnale,) 
  FROM photos 
  WHERE username LIKE '$username%'

Upvotes: 0

Rohit Subedi
Rohit Subedi

Reputation: 550

You can use LIKE MySQL clause in the query

SELECT * FROM photos WHERE username LIKE '$username%'

Upvotes: 1

John Woo
John Woo

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

Ashwini Agarwal
Ashwini Agarwal

Reputation: 4858

SELECT * FROM photos WHERE username LIKE '%$username%';

Upvotes: 2

Related Questions