Session Variable in Select Statement

19,431

Solution 1

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.

Solution 2

Basic PHP syntax rules: When embedding an array reference in a string, you do NOT use quotes on the keys:

echo "$arr['key']";   // wrong
echo "$arr[key]";     // right
echo "{$arr['key']}"; // right

Note that the {} syntax is REQUIRED if you're embedding a multi-dimensional array:

echo "$arr[foo][bar]";

is parsed as

echo $arr['foo'];
echo '[bar]';

Adding the {} makes PHP use the entire array key sequence:

echo "{$arr['foo']['bar']}";

Solution 3

Your returning a string of myusername = $_SESSION['username'], when you actually need whats stored in that. Remove the '' and append the variable to the string.

Something like this:

$sql= 'SELECT * FROM $tbl_name WHERE myusername = ' . $_SESSION['username'] . '';

Solution 4

$result = mysql_query("SELECT * FROM tbl_task where username =  '".$_SESSION['username']."' ORDER By DateAssigned ASC ");

Solution 5

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

Try this ........

100% it will work.

Share:
19,431
Tristan Krishindat
Author by

Tristan Krishindat

Updated on June 09, 2022

Comments

  • Tristan Krishindat
    Tristan Krishindat almost 2 years

    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 [email protected]

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

    $sql="SELECT * FROM $tbl_name WHERE myusername ='[email protected]'";
    $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.