0

I am trying to query and display user information from the database such as name and email. I've spent a couple days on this and read some similar threads here but have had no luck.

If I use the following query I can get what I want about a specific user and display it accordingly.

$sql = "SELECT firstname, lastname, email FROM users where username = 'blim'";

Now I want to run the same query but replace 'blim' with ($_SESSION["username"]) I get an error.

$sql = "SELECT firstname, lastname, email FROM users where username = ($_SESSION["username"])";

The reason why I thought this would work is because by using

<?php echo ($_SESSION["username"]); ?>

I am able to display a greeting specif to the user logged in so I thought I could compare that to rows in the database to retrieve information from specific columns.

4
  • 3
    try this way $sql = "SELECT firstname, lastname, email FROM users where username = '".$_SESSION["username"]."'"; Commented Oct 16, 2018 at 7:11
  • 1
    The error you are getting is telling you what's the problem. Probably you get PHP Parse error: syntax error, unexpected '"', expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in . @MyNameIs comment should work. Commented Oct 16, 2018 at 7:13
  • If you "get an error", why don't you share it with us? Commented Oct 16, 2018 at 7:15
  • 1
    You could use $sql = "SELECT firstname, lastname, email FROM users where username = '{$_SESSION['username']}";, which is only a slightly shorter version fo MyNameIs's comment. Array inside a string needs to be enclosed in {}. Also, don't forget the ' you had around 'blim'. Commented Oct 16, 2018 at 7:16

1 Answer 1

1

Try loading the username from session into its own variable, then use that variable in the query.

$username = $_SESSION["username"];

$sql = "SELECT firstname, lastname, email FROM users where username = $username";

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Yea this works. So simple yet I needed to add another step. I think I was even onto that and didn't try it for some reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.