Thursday, 30 August 2018

The session variable in the MySQL query does not work using PHP

I have the following MySQL query:

"UPDATE main SET latitude = '{$_POST['latitude']}', longitude = '{$_POST['longitude']}' WHERE idUser = '".$_SESSION['userId']."'""

But this does not work because the userId is always null in the query.
However if I echo $_SESSION['userId'], I get 32 (which is what I want).
And if I change the SQL to:
"UPDATE main SET latitude = '{$_POST['latitude']}', longitude = '{$_POST['longitude']}' WHERE idUser = 32"

It magically works!!!
What am I doing wrong?
EDIT:
I have changed the code to use prepare statements, it still does not work..
global $conn;
$stmt = $conn->prepare("UPDATE main SET latitude = ?, longitude = ? WHERE idUser = ?");
$stmt->bind_param("ssd", $_POST['latitude'], $_POST['longitude'], $_SESSION['userId']);
$stmt->execute();

It only works if I manually write the user Id I got from the echo of $_SESSION['userId']

There is an extra double quote at the end of that string .$_SESSION['userId']."'"", so how that even compiles I have no idea.

0 comments:

Post a Comment