0

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 Answers1

0

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:

Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
  • @LéoEduardoSilva 'didn't work' isn't an error message. What exactly happened, when you ran exactly what code? – Craig Ringer Oct 25 '15 at 04:52
  • I think that the first one (pg_query('SELECT * FROM mytable WHERE sess = $_SESSION');) would match my problem, but nothing happened. In other words: the problem goes on. If I change the SESSION for it's value, like Action, for example, it works. The only thing I don't know is why the SESSIN isn't working here... – Léo Eduardo Silva Oct 26 '15 at 03:43
  • @LéoEduardoSilva "nothing happens". Do you check for errors? Is there no error but zero results? If so, is there actually a corresponding row in the table? – Craig Ringer Oct 26 '15 at 03:45
  • @LéoEduardoSilva Also did you understand that the first two are *examples of what I think you are probably doing incorrectly in your current code*? I.e. they are *wrong* and *will not work*. Read the whole answer. Then try again with a parameterised query like the `pg_query_params` one shown – Craig Ringer Oct 26 '15 at 03:47
  • ain't no error. I just want to put the value that is in the SESSION in my query. Already did this, just don't know why, in this case, it isn't working... – Léo Eduardo Silva Oct 26 '15 at 22:29