$_SESSION not working inside postgres query

274 Views Asked by At

after everything to fix it, I have no more ideas and came here to find some help.

My $_SESSION isn't working inside an SELECT of postgres, but when I put like this it's OK:

The genre you selected is: <?php echo $_SESSION[genero];?>.

But inside my pg_query, it doesn't work and I know it is the $_SESSION because if I change de $_SESSION for it's value it's OK. Anybody that knows how to answer this question?

EDIT: tried put the value by $_GET and still the same problem. I don't know why it's happening, because I already did this before once... And both GET and SESSION shows the value if echo them.

1

There are 1 best solutions below

5
On

Guessing since you didn't actually show you code, but: You're almost certainly using single-quoted strings and expecting string interpolation to work, e.g.

pg_query('SELECT * FROM mytable WHERE sess = $_SESSION');

or

$dbh->exec('SELECT * FROM mytable WHERE sess = $_SESSION')

If so: string interpolation in PHP is performed only on double-quoted strings. More importantly though, don't use string interpolation in SQL unless you're absolutely sure the value can't be set or changed by the user. Even then, preferably don't. Use parameterized queries, e.g.

pg_query_params('SELECT * FROM mytable WHERE sess = $1', array($_SESSION));

or

$stmt = $dbh->prepare('SELECT * FROM mytable WHERE sess = :sess');
$stmt->bindParam(':sess', $_SESSION);
$stmt->execute();

See: