Use of superglobals within a session

2

index.php

<?php 
    include './db_unifacex.php';
    session_start();
    $_SESSION['contador']=0;
?>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="refresh" content="0.1;URL=http://localhost/geraCode/content.php">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link href="jquery/jquery-3.1.1.min.js" type="text/javascript">
        <link type="text/css" href="style/style.css" rel="stylesheet">
    </head>
</html>


content.php

    <?php 
    include './db_unifacex.php';
    session_start();
?>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link href="jquery/jquery-3.1.1.min.js" type="text/javascript">
        <link type="text/css" href="style/style.css" rel="stylesheet">
    </head>
    <body style="background-image: url(imgs/bk.jpg);">
        <div class="header">
            <img class="logo" src="imgs/cife_logo.png">
            <div class="titulo">
                Gerador de Newslatter
            </div>
            <hr>
        </div>
        <div class="container">
            <div class="col-md-12">
                <div class="col-md-6">
                    <h2> <?php echo $_SESSION['contador']+1;?>º Notícia </h2>
                    <form class="formulario" action="validar.php" method="post">
                        <div class="form-group">
                            <label>Titulo:</label> <input required type="text" name="titulo" class="form-control">
                        </div>
                        <div class="form-group">
                            <label>Mensagem:</label> <textarea required name="mensagem" class="form-control"></textarea>
                        </div>
                        <div class="form-group">
                            <label>Foto:</label><input required type="text" name="foto" class="form-control">
                        </div>
                        <div class="form-group">
                            <input id="enviar" type="submit" name="enviar" class="form-control btn-default" value="Próximo">
                        </div>
                    </form>
                    <form action="fim.php" method="post">
                        <div class="form-group">
                            <input id="enviar" type="submit" name="fim" class="form-control btn-default btn-disable finalizar"  <?php if($_SESSION<4){echo 'disabled';}?> value="Finalizar">
                        </div>
                    </form>
                </div>
                <div class="col-md-6 ">
                    <h2>Pré-visualização: <?php echo $_SESSION['contador']+1;?>º Notícia</h2>
                    <div class="panel panel-defaul">
                        <div class='panel-body'>
                            <?php
                                $row = row($_SESSION['contador']);
                                echo $row;
                                $linha = ultimos();
                                var_dump($linha);
                            ?>
                        </div>
                    </div>
                </div>
            </div>    
        </div>
        <div class="footer">
            <hr>
            <div class="rodape">
                Produzido por Rafael Pessoa
            </div>
        </div>
        <?php fim();?>
    </body>
</html>


validar.php

    <?php
include ('./db_unifacex.php');
session_start();
//Variáveis recebidas do index.php
    $titulo = $_POST['titulo'];
    $mensagem = $_POST['mensagem'];
    $foto = $_POST['foto'];

//Variáveis do banco de dados
    $host = "mysql:host=localhost;dbname=boletim";
    $passwd = "senha";
    $username = "user";
//Conexão com o banco
    try {
        $conn = new PDO($host, $username, $passwd);
    } catch (Exception $exc) {
        echo $exc->getMessage();
    }
//Inserção dos dados
    $stmt = $conn->prepare("INSERT INTO noticia(titulo, mensagem, enderecoUri) VALUES(:tit, :mens, :end)");
    $stmt->bindParam(":tit", $titulo);
    $stmt->bindParam(":mens", $mensagem);
    $stmt->bindParam(":end", $foto);
    $stmt->execute();  
//Soma da sessão
    $_SESSION['contador']++;
    ?><a href="index.php"><button>Voltar</button></a>

I'm wondering if you can change the value of a superglobal variable. I have to pass a variable from one page to another and then go back to the old page plus +1.

In other words, I need a counter superglobal . I was trying to do this with superglobal $_SESSION , but I realized it did not work.

    
asked by anonymous 16.01.2017 / 21:43

1 answer

1

You have something like $_SESSION . But since you did not enter the code, I'll give you an example: pagina1.php

// inicias as sessoes
session_start();
//verifica se a sessao contador nao existe
if(!isset($_SESSION['contador'])){
//se ela nao existir, inicio ela com o valor padrao 0
$_SESSION['contador']=0;
}
else{
// mas se ela existir, apenas somo +1
$_SESSION['contador']++;
}

Ai page2.php would be the same code:

 // inicias as sessoes
session_start();
//verifica se a sessao contador nao existe
if(!isset($_SESSION['contador'])){
//se ela nao existir, inicio ela com o valor padrao 0
$_SESSION['contador']=0;
}
else{
// mas se ela existir, apenas somo +1
$_SESSION['contador']++;
}

Or the same code in a well-summed way using the ternary operator:

// inicias as sessoes
session_start();
!isset($_SESSION['contador'])?$_SESSION['contador']=0:$_SESSION['contador']++;
  

For those who do not know, this operator has this syntax

     

(condition) ? here the condition is true : here it is false;

The possible error you are probably having is that you are not giving session_start() on all pages. I hope I have helped

    
16.01.2017 / 22:20