Undefined variable when trying to add a value in the session

Asked

Viewed 114 times

0

The template.php file:

HTML code:

<html>
...

<table border="3">
        
            <tr>
                <th>Tarefas</th>
                <th>Descrição</th>
                <th>Prazo</th>
                <th>Prioridade</th>
                <th>Concluída</th>
            </tr>
            
            <?php foreach($lista_tarefas as $tarefa){ ?>
                
                <tr>
                    <td><?=$tarefa['nome'];?></td>
                    <td><?=$tarefa['descricao'];?></td>
                    <td><?=$tarefa['prazo'];?></td>
                    <td><?=$tarefa['prioridade'];?></td>
                    <td><?=$tarefa['concluida'];?></td>
                </tr>
                
            <?php } ?>
        
        </table>

...
</html >    

PHP code:

<?php 
    
        session_start();
        
        if(isset($_GET['nome']) && $_GET['nome'] != ''){
            $tarefa = array();
            $tarefa["nome"] = $_GET["nome"];
        
        if(isset($_GET['descricao'])){
            $tarefa['descricao'] = $_GET["descricao"];
        }else{
            
            $tarefa['descricao'] = '';
        }
        
        if(isset($_GET["prazo"])){
            
            $tarefa['prazo'] = $_GET['prazo'];
            
        }else{
            
            $tarefa['prazo'] = '';
        }
        
        $tarefa['prioridade'] = $_GET['prioridade'];
        
        if(isset($_GET['concluida'])){
            $tarefa['concluida'] = $_GET["concluida"];
        }else{
            
            $tarefa['concluida'] = '';
        }
        
        $_SESSION['lista_tarefas'] = array($tarefa);
            
        
        }
        
        include "template.php";

And on the part of view

Given errors:

Notice: Undefined variable: lista_tarefas in

Warning: Invalid argument supplied for foreach() in

Does anyone know how to display and not show these errors?

1 answer

0


The problem is that you are trying to access an undefined variable.

<?php foreach($lista_tarefas as $tarefa){ ?>
    <tr>
        <td><?=$tarefa['nome'];?></td>
        <td><?=$tarefa['descricao'];?></td>
        <td><?=$tarefa['prazo'];?></td>
        <td><?=$tarefa['prioridade'];?></td>
        <td><?=$tarefa['concluida'];?></td>
    </tr>
<?php } ?>

In this section you use $lista_tarefas as if it were defined as $_SESSION["lista_tarefas"], but this conversion of the session to a variable is not done alone. You need to set the value of the variable:

$lista_tarefas = $_SESSION["lista_tarefas"];
  • @Nitroushang please delete the above comments to not pollute the site.

Browser other questions tagged

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