Search code examples
phpmysqlsession-variables

Session Variable in Select Statement


On one page i have it to show the user who logged in username which works perfectly fine.

echo "Welcome, ".$_SESSION['username']

I wanna create a Select Statement which uses the same variable as above to pull all data for that user.

Example Username is jsmith@gmail.com

I used this to see if the coding works which it did.

$sql="SELECT * FROM $tbl_name WHERE myusername ='jsmith@gmail.com'";
$result=mysql_query($sql);

But I wanna use the variable; I tried the code below but it didn't work.

$sql="SELECT * FROM $tbl_name WHERE myusername ='$_SESSION['username']'";
$result=mysql_query($sql);

I know for sure it has to do with the SELECT statement using the variable, im not sure if i am relating to the variable correctly.

Help will be greatly appreciated.


Solution

  • Try using

    $sql="SELECT * FROM $tbl_name WHERE myusername ='{$_SESSION['username']}'";
    

    This syntax where you use the variable replacement capacity of PHP in string is much easier to read, at-least when you have to replace multiple variables in a string.