Tristan Krishindat
Tristan Krishindat

Reputation: 53

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 [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.

Upvotes: 3

Views: 23163

Answers (7)

Yogaraja C A
Yogaraja C A

Reputation: 11

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

Try this ........

100% it will work.

Upvotes: 1

Billy Frawl
Billy Frawl

Reputation: 11

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

Upvotes: 1

user2541120
user2541120

Reputation:

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

$result=mysql_query($sql);`

Corrected code above.

There will be no quotes for username inside session.

Upvotes: 0

Vivek Sadh
Vivek Sadh

Reputation: 4268

You have not ended your query:-

$sql="SELECT * FROM $tbl_name WHERE myusername ='$_SESSION['username']'; // double quotes missing

Even the Stackoverflow code highlighter shows it.

Upvotes: 0

Marc B
Marc B

Reputation: 360882

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']}";

Upvotes: 2

bansi
bansi

Reputation: 57062

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.

Upvotes: 11

Matthew Camp
Matthew Camp

Reputation: 876

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'] . '';

Upvotes: 1

Related Questions