postmodern.life
postmodern.life

Reputation: 35

Unsure how to use php variables in mysql

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);

Upvotes: 1

Views: 75

Answers (3)

e4c5
e4c5

Reputation: 53734

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.

Upvotes: 5

rulo4
rulo4

Reputation: 105

$sql = "SELECT count(*) exists FROM fgusers3 WHERE username = '".$_SESSION['username']."'";
$result =  $conn->query($sql);
echo  $result[0]['exists'];

Upvotes: 1

shubham715
shubham715

Reputation: 3302

Try this:-

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

?>

Upvotes: 1

Related Questions