Session variable is empty when loading page set in <form action=""

Asked

Viewed 143 times

0

I’m beginner in php, I’m doing a quiz as a college job...

By clicking submit, using a echo in the variable $_SESSION['id'], normally displays the content (receives the last id inserted in the database). However, when <form action="resultado.php" method="post"> and load the page is returned.

Notice: Undefined index: id in C: xampp htdocs inteligencias result.php on line 21

I need to recover this id on another page to perform sql query with the result.

questoes.php :

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Questionário</title>
</head>
<body>
<?php
include("conecta.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $st = $db->prepare("INSERT INTO usuarios (dt_resp) VALUES (NOW())");
    $st->execute();
    $_SESSION['id'] = $db->lastInsertId();

    for ($i = 1; $i <= 28; ++$i) {
        $chave = 'P'.$i;
        $stmt = $db->prepare("INSERT INTO respostas (RESPOSTA, IDPERGUNTA, IDUSUARIO) VALUES (:resp, :perg, :id)");
        $stmt->bindParam(":resp", $_POST[$chave]);
        $stmt->bindParam(":perg", $i);
        $stmt->bindParam(":id", $ident);
        $stmt->execute();
    }

}
?>
<form action="resultado.php" method="post">    <!-- resultado.php -->
    <legend id="titulo">Inteligências Múltiplas</legend>
    <?php
    try {
        foreach ($db->query("SELECT * FROM perguntas") as $perguntas) {
            echo "<h4> $perguntas[ID]. $perguntas[ENUNCIADO] </h4>";
            echo "<input type ='radio'  id='concordo' name='P$perguntas[ID]' value = 'C' >Concordo<br>";
            echo "<input type ='radio'  id='discordo' name='P$perguntas[ID]' value = 'D' checked=checked >Discordo <br>";
        }
        $db = null;
    } catch (PDOException $e) {
        echo "Erro!: ".$e->getMessage()."</br>";
    }
    ?>
    <br>
    <input type="submit" name="acao" value="ENVIAR">
</form>
</body>
</html>

php result.:

<?php
if (!isset($_SESSION)) {
    session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Resultado</title>
</head>
<body>

<?php
include("conecta.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    echo $_SESSION['id'];
}
?>
</body>
</html>
  • You have already run this test: <?php session_start(); ?>?

  • Place the attribute name of radio Buttons as name='id'.

  • @Taffarelxavier

  • @Augustovasques need to capture the id of the question coming from the database to enter the answer, so theoretically I can’t change it. $_SESSION['id'] refers to the last id inserted in the user table.

  • But the question raised in the question is the fact that you do not have the 'id' parameter when you send the request to php result. that’s why it makes the mistake Undefined index. In the <form> add an Hidden field whose name='id' and value=$_SESSION['id']

1 answer

2

To recover the id, which in this case is a key in the session, and not in the GET or POST matrices, you must save it in the sessão, and you’re not doing it, so the mistake.


In fact, your mistake is easier than we could imagine, then you have programming logic error. As you edited your codes, it became easier to notice it.

First of all, you are not saving a value with the key id in session unfortunately.

Let’s remember, about php, that the error Notice: Undefined index: does not occur only with $_GET and $_POST or, indirectly, in forms, but actually occurs at the moment when we try to fetch a value in an array by its index, but the same does not exist.

Honestly, it’s amazing how many people don’t know what they’re saying:
How to solve a Notice: Undefined index?
https://www.homehost.com.br/blog/tutoriais/php/notice-undefined-index-php/

BATTER: This question, in English, answers how I think: https://stackoverflow.com/questions/18731693/undefined-index-with-php-sessions

"The reason for these errors is that you are trying to read a matrix key that does not exist." In this case, in the $_SESSION matrix. Ready! That’s exactly it.

Now, let’s go to your codes:

Look at it: in the file questoes.php, You’re doing the following: $_SESSION['id'] = $db->lastInsertId();, but as this will be saved in the matrix $_SESSION, which is within a condition, in which a POST request is required?

Unless another file requests the file questões.php, it is impossible to have a key in your session with this name: id, thus preventing its recovery later as you are trying to do in the file resultado.php.

See an example using your same files, of course I took some things, I have no way to add them, for example your settings files.

Questoes.php

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Questionário</title>
</head>
<body>
<?php
//include("conecta.php");
//Veja que adiciono um valor com a chave id, somente para demonstração.
//Você já pode clicar em enviar para ir ao arquivo resultado.php, verás que aparecerá um valor aleatório.
$_SESSION['id'] = rand();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $st = $db->prepare("INSERT INTO usuarios (dt_resp) VALUES (NOW())");
    $st->execute();
    $_SESSION['id'] = $db->lastInsertId();

    for ($i = 1; $i <= 28; ++$i) {
        $chave = 'P'.$i;
        $stmt = $db->prepare("INSERT INTO respostas (RESPOSTA, IDPERGUNTA, IDUSUARIO) VALUES (:resp, :perg, :id)");
        $stmt->bindParam(":resp", $_POST[$chave]);
        $stmt->bindParam(":perg", $i);
        $stmt->bindParam(":id", $ident);
        $stmt->execute();
    }

}
?>
<form action="resultado.php" method="post">    <!-- resultado.php -->
    <legend id="titulo">Inteligências Múltiplas</legend>
    <?php
   /* try {
        foreach ($db->query("SELECT * FROM perguntas") as $perguntas) {
            echo "<h4> $perguntas[ID]. $perguntas[ENUNCIADO] </h4>";
            echo "<input type ='radio'  id='concordo' name='P$perguntas[ID]' value = 'C' >Concordo<br>";
            echo "<input type ='radio'  id='discordo' name='P$perguntas[ID]' value = 'D' checked=checked >Discordo <br>";
        }
        $db = null;
    } catch (PDOException $e) {
        echo "Erro!: ".$e->getMessage()."</br>";
    }*/
    ?>
    <br>
    <input type="submit" name="acao" value="ENVIAR">
</form>
</body>
</html>

Result.php

<?php
if (!isset($_SESSION)) {
    session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Resultado</title>
</head>
<body>
<form method="POST">
<button>Enviar</button>
</form>
<?php
//include("conecta.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Por que não aparece o erro?
//Simples: você salvou na sessão um valor com a chave `id`, lá, quando iniciou o arquivo questoes.php
    var_dump($_SESSION);
    echo $_SESSION['id'];
}

?>
</body>
</html>

Completion

Unfortunately, to solve your problem, I would need to understand your business rules, your rules of application. You need to save the id in the session otherwise, perhaps, using ajax or using the $_GET method, there, in the file, questoes.php. However, one thing is quite certain: there is programming logic error (php) in its logic.

Browser other questions tagged

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