Session PHP does not work

Asked

Viewed 621 times

0

I’m starting with PHP and when trying to do an exercise proposed in an apostille, my $_Session variable is not working as it should, can you tell me which error in the code?

<?php session_start() ?>

<html>
    <head>
        <title>Contatos</title>
    </head>
    <body>
        <h1>Contatos</h1>
        <form>
            <fieldset>
                <legend>Adicionar novo contato</legend>
                <label>
                    Nome: <input type="text" name="nome" />
                </label>
                <label>
                    Telefone: <input type="text" name="telefone" />
                </label>
                <label>
                    Email: <input type="text" name="email" />
                </label>
                <input type="submit" value="Salvar Contato" />
            </fieldset>
        </form>

    <?php

        $nome = array();
        $telefone = array();
        $email = array();

        if (isset($_GET["nome"]))
        {
            $_SESSION["a"] = $_GET["nome"];
            $_SESSION["b"] = $_GET["email"];
            $_SESSION["c"]  = $_GET["telefone"];                    
            $nome[] = $_SESSION["a"];
            $email[] = $_SESSION["b"];
            $telefone[] = $_SESSION["c"];
        }

    ?>
    <table>
    <tr>
        <th>Nome</th>
        <th>Telefone</th>
        <th>E-mail</th>
    </tr>
    <tr>
    <?php foreach ($nome as $nome) : ?>
            <td><?php echo $nome ?></td>
    <?php endforeach; ?>
    <?php foreach ($telefone as $telefone) : ?>
            <td><?php echo $telefone ?></td>

    <?php endforeach; ?>
    <?php foreach ($email as $email) : ?>
        <td><?php echo $email ?></td>
    <?php endforeach; ?>
    </tr>
    </table>
</body>
</html>

1 answer

1


Change this excerpt:

        $_SESSION["a"] = $_GET["nome"];
        $_SESSION["b"] = $_GET["email"];
        $_SESSION["c"]  = $_GET["telefone"];                    
        $nome[] = $_SESSION["a"];
        $email[] = $_SESSION["b"];
        $telefone[] = $_SESSION["c"];

To:

        $_SESSION["nome"] = $_GET["nome"];
        $_SESSION["email"] = $_GET["email"];
        $_SESSION["telefone"]  = $_GET["telefone"];                    

So we can pass the variables inside Sesssion already

  • And for the exits? how would I do? I want to store all the entries in $_SESSION and then show them. D

  • You can give an echo $_SESSION['name']; or if you give a print_r($_SESSION), you will see what was recorded and the values of each one.

Browser other questions tagged

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