-1

I am trying to execute a SQL query that will give me all usernames from my table which begin with 'Ana%'.

There are two rows like it:

  1. Ana
  2. Anastacia

My code is like:

$value="Ana"
$sql=mysql_query("Select username from users where username like {"."'".$value."%"."'}"); 

$row=mysql_fetch_array($sql);

print_r($row);

The problem is I get information only about user Ana, not Ana and Anastasia like it should be.

I tried without brackets {}, but it did not work.

elixenide
  • 44,308
  • 16
  • 74
  • 100

2 Answers2

3

Your LIKE clause should be

like '".$value."%'");

No { or }, and no need for all the extra concatenation. So the entire command would be

$sql=mysql_query("Select username from users where username like '".$value."%'");

That said, the mysql_* functions are deprecated, and you are wide open to SQL injection, so you have bigger problems to worry about. You need to use PDO or MySQLi and prepared statements.

Edit: Also, you are not retrieving both rows of your data. mysql_fetch_array() only fetches one row at a time, so you need to use a loop, like this:

while($row=mysql_fetch_array($sql)) {
    print_r($row);
}
elixenide
  • 44,308
  • 16
  • 74
  • 100
  • This also returns only Ana ..:( I will try with MySQLi – user2854939 Jun 04 '15 at 20:51
  • @user2854939 Make sure you are retrieving both rows. [`mysql_fetch_array()`](http://php.net/manual/en/function.mysql-fetch-array.php) only fetches one row at a time, so you need to use a loop. See my edit above. – elixenide Jun 04 '15 at 22:11
  • @user2854939 Please remember to accept this answer! :) – elixenide Jun 04 '15 at 22:11
0

Try this:-

$sql=mysql_query("Select username from users where username like '".$value."%'");
Ashwani
  • 692
  • 2
  • 6
  • 16