Reputation: 211
I tried to execute this query -
$sql="INSERT INTO REGISTRATIONS VALUES ('$_SESSION['fname']', '$_SESSION['username']', '$_SESSION['height']', '$_SESSION['image']');";
And this one as well -
$sql="INSERT INTO REGISTRATIONS VALUES ($_SESSION['fname'], $_SESSION['username'], $_SESSION['height'], $_SESSION['image']);";
But both these returns an error. So i stored the session variables into normal php variables. and tried to execute the query -
$name = $_SESSION['fname'];
$username = $_SESSION['username'];
$height = $_SESSION['height'];
$image = $_SESSION['image'];
$sql="INSERT INTO REGISTRATIONS VALUES ('$name', '$username', '$height', '$image');";
And it worked.
But i want to know why the first two didn't work and why we have to save Session into another variable to get it to work?
Please help :)
Upvotes: 0
Views: 6312
Reputation: 631
You have have a syntax error in this code
$sql = "
INSERT INTO REGISTRATIONS
VALUES (
'$_SESSION['fname']',
'$_SESSION['username']',
'$_SESSION['height']',
'$_SESSION['image']'
);
";
'$_SESSION['fname']'
is causing an error here. You can't access array indexes inside a string without special syntax (see below).
Separate the string and variables with the concatenation operator, .
$sql = "
INSERT INTO REGISTRATIONS
VALUES ('"
.$_SESSION['fname'].
"', '"
.$_SESSION['username'].
"', '"
.$_SESSION['height'].
"','"
.$_SESSION['image'].
"');";
or use PHP's variable interpolation, see "Complex (curly) syntax". This is the prefered way.
$sql = "
INSERT INTO REGISTRATIONS
VALUES (
'{$_SESSION['fname']}',
'{$_SESSION['username']}',
'{$_SESSION['height']}',
'{$_SESSION['image']}'
);
";
Please note, the this only works on double quoted strings.
Upvotes: 3
Reputation: 3329
you can use
echo "$_SESSION[name]";
echo "{$_SESSION['name']}";
see http://php.net/manual/en/language.types.string.php#language.types.string.parsing.simple
If you want to have a reason why this was done so, well, I can't help you there. But as always: PHP is old and has evolved a lot, thus introducing inconsistent syntax.
also check how to use associated array inside double quotes
http://php.net/manual/en/language.types.array.php#language.types.array.foo-bar
http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex
Upvotes: 0
Reputation: 86
Try these
$sql="INSERT INTO REGISTRATIONS VALUES ('".$_SESSION['fname']."', '".$_SESSION['username']."', '".$_SESSION['height']."', '".$_SESSION['image']."')";
Upvotes: 2