PHP because $_SESSION[name] - without quotation marks - is accepted and does not give error in INSERT and when destroying Sessions gives error in unset($_SESSION[name]

Asked

Viewed 53 times

0

I retrieve the form information with foreach

 foreach($_POST as $chave=>$valor){
    $_SESSION[$chave] = $conexao-> real_escape_string($valor);
 }

what it produces

 $_SESSION[nome] 
 SESSION[sobrenome] 
 etc......

and do INSERT thus without returning any kind of error

 VALUES(
       '$_SESSION[nome]',
       '$_SESSION[sobrenome]',
       ...............

  $confirma = $conexao->query....

But by destroying the Sesssions in the following way

  if($confirma){
   unset($_SESSION[nome],
         $_SESSION[sobrenome],
         ..............

returns several errors, one for each Session, for example

PHP Warning:  Use of undefined constant nome - assumed 'nome' (this will throw an Error in a future version of PHP) in

2 answers

1

$_SESSION is a list that takes (in this case) a String as "parameter" (which is actually the name of the index), not the quotes, but "what" you put there.

In the first case $chave is a String variable, so you don’t need the quotes.

In the second:

VALUES(
       '$_SESSION[nome]',
       '$_SESSION[sobrenome]',
       ...............

Despite not having put the complete code, we know that querys are strings, so all that already wrote this in quotes, so the compiler understands that there are strings so no errors.

In the third the error happens because it is not a String, and adapting to this context, it is not inside a String (as in the second case), so it does not accept the type passed, which in this case, for not having the $ is considers a constant that has not been declared.

1

I will be as direct as possible to the problem. If you have:

$x = "nome"; 

And makes:

$_SESSION[$x] = "Rui";

So it corresponds to do :

$_SESSION["nome"] = "Rui";

Note that here the name came out with quotes because it is a string, which was the contents of the variable $x. This is different from doing:

$_SESSION[nome] = "Rui";

In the latter case the interpreter cannot understand what the nome and assumes that it is an undefined constant, showing such a warning that you see on the page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.