Difficulty creating sessions to save form data

Posted on

Question :

I have a form that has 6 fields and a button that allows the user to repeat these 6 fields to add more data.

I want to save the data in a session, and write to DB only when the user completes the fill.

I do not know how to create the sessions right, the searches I did did not help much. Here is the code:


$query= mssql_query($sql) or die ('Erro ao realizar consulta ao banco de dados');


//Carrega a página com os produtos de acordo com o grupo escolhido

//função para adicionar mais produtos

<div class="grid_24 cinza subtitulo">Nova Requisição</div>
<!-- formulário para requisição de produtos  -->
<form action="novaRequisicao.php" method="POST">    
<div id="clona">
<div class="grid_7">
    Selecione um grupo de produtos<br>
    <select name="grupoProdutos[]" id="grupoProdutos" required="required">
        <option value=""> Selecione</option>
            echo " <option value='".$codGrupo."'>".$grupo." </option> ";
<div id="produtos" ></div>
<div id="aqui"></div>



$grupoProdutos = $_GET['grupoProdutos'];
$sql=mssql_query("SELECT * FROM supervisor.PRODUTO WHERE COD_GRUPO='$grupoProdutos' ORDER BY DES_PRODUTO");
<div class="grid_10">
echo "Selecione um produto<br> <select name='produto[]' required='required'>";
echo " <option value=''>Selecione</option> ";
while ($row=mssql_fetch_array($sql)) {
    echo " <option value='$id'>".$nome."</option> ";
echo "</select>";

Preencha se o produto não está na listagem<br> 
<input type="text" name="naoListado[]" class='largeInput' placeholder='Nome do produto não listado'>
<div class="grid_4">
<input type="number" name="quantidade[]" required="required" class="shortInput" min="1">
<input type="text" name='tipo[]' placeholder='Kg, ml, etc.'>
<div class="grid_6">
    <textarea  name="observacoes[]" cols="30" rows="5"></textarea>
<div class="grid_2">
<button id="add">+</button>
<div class="grid_2">
<input type="submit" value="Finalizar requisição" class="emerland text-white but">



Answer :

To create instances of a session, you must first initialize a session, never after, or return an error.

Initialize a session:


The function should always be at the beginning of the code, never after, because it is a header , and the headers should always be sent before any other information. p>

To create variables of this same session, and sign values to them, use the variable $_SESSION['indice_da_sessao'] , see:

$_SESSION['meu_nome'] = "Edilson";
// Ou ainda
$meu_nome = "Edilson";
$meu_codigo = 123;
$_SESSION['meu_nome'] = $meu_nome;
$_SESSION['meu_codigo'] = $meu_codigo;

After using these values, you can simply discard the current session using session_destroy() as done on login systems or even unset($_SESSION['indice_da_sessao']) to undo a specific session.

To use the header() function while a session instance has not yet been destroyed, you must use exit() to avoid errors, with multiple headers defined.

To store settings, non-sensitive information, or those that do not pose a risk to the system, are usually used cookies

Other references:

Sessions – PHP.net

Cookies – PHP.net

Error: Heards already sent – SOen


In your novaRequisicao.php , add session_start() :

$query= mssql_query($sql) or die ('Erro ao realizar consulta ao banco de dados');

if ( empty(session_id()) ) { session_start(); }

From there, you can use the global variable of $_SESSION , which is an associative array . So I could use something like $_SESSION['produtos'] and add things to it.


Leave a Reply

Your email address will not be published. Required fields are marked *