0

I can't get the logged in user in the code, can you please help me to figure it out:

the code which is not working:

 $result = mysql_query("SELECT * FROM clients WHERE user = '$_SESSION['user']['username']'")
            or die(mysql_error());  

but it is working for showing it thought, in here:

echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');

thanks in advance for any help.

Danishcj
  • 3
  • 2

2 Answers2

1

There are two solutions to this. The first is to define a new variable to contain the $_SESSION['user']['username'] value and the second is to enclose $_SESSION['user']['username'] in curly braces (see: Strings - variable parsing for more information).

Solution 1

$username = $_SESSION['user']['username'];

mysql_query("SELECT * FROM clients WHERE user = '$username'")
        or die(mysql_error());

Solution 2

mysql_query("SELECT * FROM clients WHERE user = '{$_SESSION['user']['username']}'")
        or die(mysql_error());

In addition to this, if one is only accessing the top-level of the array (e.g. $_SESSION['username'] rather than $_SESSION['user']['username']) one can simply remove the quotes around the key name:

mysql_query("SELECT * FROM clients WHERE user = '$_SESSION[username]'")
        or die(mysql_error());

However, it should be worth pointing out that mysql functions are deprecated and that your code is vulnerable to SQL injection. You should look into using PDO or mysqli prepared statements.

Michael
  • 11,912
  • 6
  • 49
  • 64
0

You can try this, please avoid using mysql functions anymore, and this not a hackproof code. Pleae make it

   $user = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');

   mysql_query("SELECT * FROM clients WHERE user = '".$user."'")
        or die(mysql_error());
Adil Abbasi
  • 3,161
  • 1
  • 40
  • 35