1

This is returning a blank screen. What specifically do I have to do to test if a session variable is in the database and return the corresponding value from a different column?

$sql = "SELECT email FROM fgusers3
WHERE username = '$_SESSION['username']'";
$result = $conn->query($sql);

3 Answers 3

5

The most correct way to use PHP variables in PHP is to use prepared statements.

$query = $dbh->prepare("SELECT email FROM fgusers3 where username=:username")
$query->execute(array(":username"=>$_SESION['username']));

This is far superior to solution that involve direct string concatenation, and still better than solutions that involve string escaping.

The reason that you should not use direct string concatenation as in some of the other answers is that it leads to SQL Injection. An attacker can easily gain complete access to your database by using carefully crafted strings.

The above example uses PDO, which in my not very humble opinion is a far superior API to mysqli. Mysqli also has prepared statements It's usage is similar but the syntax is different.

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

3 Comments

If PDO this is correct. mysqli is slightly different, but the same general idea.
hi @tadman, I am always promoting PDO over mysqli. Will update answer
Oh, I agree PDO is much better, but it's not clear from the question if PDO is being used. Just saying.
1

Try this:-

<?php
$sql = "SELECT email FROM fgusers3 WHERE username = '".$_SESSION['username']."'";
$result = $conn->query($sql);

?>

1 Comment

sorry but this is definitely not the way to do it.
1
$sql = "SELECT count(*) exists FROM fgusers3 WHERE username = '".$_SESSION['username']."'";
$result =  $conn->query($sql);
echo  $result[0]['exists'];

1 Comment

Switching from interpolation to concatenation does almost nothing to fix the problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.