简体   繁体   中英

How to use Session Variable in MySQL Query

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

Problem

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

Solution

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.

试试这些

$sql="INSERT INTO REGISTRATIONS VALUES ('".$_SESSION['fname']."', '".$_SESSION['username']."', '".$_SESSION['height']."', '".$_SESSION['image']."')";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM