Problem passing variable from one screen to another

Asked

Viewed 170 times

0

Here’s the deal. I have a problem using $_SESSION in PHP. I’m starting now, so excuse me if I haven’t done the login system the right way.

I have a login screen that basically runs this code:

        <?php

session_start();

include_once('classes/Database.php');

if (isset($_SESSION['logged_in'])) {

    // Abre a página system.php - Outra tela, onde o nome deve aparecer.

} else {
    if (isset($_POST['form_email'], $_POST['senha'])) {
        $email = $_POST['form_email'];
        $password = md5($_POST['senha']);
        $nome = "";

        if (empty($email) or empty ($password)) {
            $error = "Todos os campos são obrigatórios!";
        } else {
            $query = $pdo->prepare("SELECT * FROM usuarios WHERE u_email = ? AND u_senha = ?");
            $query->bindValue(1, $email);
            $query->bindValue(2, $password);

            $query->execute();

            $num = $query->rowCount();
            if ($num == 1) {
                // Pega o nome do usuário que logou no sistema

                $stmt = $pdo->prepare("SELECT u_nome AS nome FROM usuarios WHERE u_id = '$num'");
                $stmt->bindValue(1, $nome);
                $stmt->bindValue(1, $num);
                $stmt->execute();

                $linha = $stmt->fetch(PDO::FETCH_ASSOC);

                $nome = $linha['nome'];
                $_SESSION['nome'] = $nome;
                $_SESSION['logged_in'] = true;
                echo $_SESSION['nome'];

                header('Location: system.php');
                exit();
            } else {
                $error = 'Email ou senha incorretos!';
            }
        }

    }

    ?>

     // Aqui mostra o código html da página de login

<?php }

Following the code structure, you notice that if you found the user in the database I take the variable one, step as the ID and select the user name, if I take the header('Location: ...') I will be on the screen and show the user name, works perfectly. See:

Displays the correct name of $_SESSION['nome']. But when starting on the page of system.php Session simply appears to be deleted and gives undefined variable error.

inserir a descrição da imagem aqui

Code system.php

<?php

session_start();

include_once('classes/Database.php');

echo $_SESSION['nome']; // Aponta erro aqui, lógico

require_once './page_structure.php';

?>

// Aqui mostra o código html da página system.php

If you can help me, the idea is to show like a Welcome followed by the user name.

Remark: A $_SESSION['logged-in'] shows normal in system.php, with value = 1.

  • You changed the question code and now the answer is out of tune. You should not change the answer by posting the code with the solution. Post the correct one as the answer. Also, the way the second query is does not require $stmt->bindValue(1, $email); It would only be necessary if it were WHERE u_email = ?");

  • I went back to the old version and put the current code in response. Thanks for the help!

2 answers

2

// Takes the name of the user who logged on to the system

Wrong

$stmt = $pdo->prepare("SELECT u_nome AS nome FROM usuarios WHERE u_id = '$num'");
$stmt->bindValue(1, $nome);
$stmt->bindValue(1, $num);

Correct:

$stmt = $pdo->prepare("SELECT u_nome AS nome FROM usuarios WHERE u_id = ?");
$stmt->bindValue(1, $id);

$stmt->bindValue(1, $name);

$stmt->bindValue(1, $name);

Where the variable $id you will have return in the first select

$row = $query->fetch(PDO::FETCH_ASSOC);

$id = $row['id'];

$num = $query->rowCount(); returns 1 if there is any user with the data informed, therefore if the $query was running would always return the user name with u_id=1

I do not see the need for two querys to achieve the desired, only one.

<?php

session_start();

include_once('classes/Database.php');

if (isset($_SESSION['logged_in'])) {

    // Abre a página system.php - Outra tela, onde o nome deve aparecer.

} else {
        if (isset($_POST['form_email'], $_POST['senha'])) {
            $email = $_POST['form_email'];
            $password = $_POST['senha'];
            $nome = "";

            if (empty($email) or empty ($password)) {
                $error = "Todos os campos são obrigatórios!";
            } else {
                $query = $pdo->prepare("SELECT * FROM usuarios WHERE u_email = ? AND u_senha = ?");
                $query->bindValue(1, $email);
                $query->bindValue(2, $password);

                $query->execute();

                $row = $query->fetch(PDO::FETCH_ASSOC);

                $num = $query->rowCount();

                if ($num == 1) {
                    // Pega o nome do usuário que logou no sistema

                    $nome = $row['nome'];
                    $_SESSION['nome'] = $nome;
                    $_SESSION['logged_in'] = true;

                    header('Location: system.php');
                    exit();
                } else {
                    $error = 'Email ou senha incorretos!';
                }
            }
       }

}

echo $error;
?>
  • Leo, I made the changes but the error persists. It is printing the correct name on the login page, but if I load the system.php error gives error.

  • I made a correction in response, typo, was WHERE u_id = = ? the correct is WHERE u_id = ? See if that’s it

  • Error persists in... I think it’s some problem with Session, because on the login screen you save everything right, but it seems that the value is lost and on the screen of system.php gives the error shown in the question.

  • It closes the condition, has html code in the middle of it

  • So I managed to fix the problem. It was simple, I will update the code. I made other changes as well. It was just taking off Exit(); I don’t know why, but solved

  • Really Leo, it was not Exit() that was causing the error. I did a series of tests by taking out certain lines of code and altering it and I couldn’t find the location of the modification that started working. I’m going through the code above now

  • I changed the code to the current one, which is working. Only God to discover this error, I can’t believe I solved.

Show 2 more comments

1


Error resolution:

Code of the Login page:

<?php

session_start();

include_once('classes/Database.php');

if (isset($_SESSION['logged_in'])) {

    // Abre a página system.php
    header('Location: pages/system.php');

} else {
    if (isset($_POST['form_email'], $_POST['senha'])) {
        $email = $_POST['form_email'];
        $password = md5($_POST['senha']);
        $nome = "";

        if (empty($email) or empty ($password)) {
            $error = "Todos os campos são obrigatórios!";
        } else {
            $query = $pdo->prepare("SELECT * FROM cms_usuarios WHERE u_email = ? AND u_senha = ?");
            $query->bindValue(1, $email);
            $query->bindValue(2, $password);

            $query->execute();

            $num = $query->rowCount();
            if ($num == 1) {
                // Pega o nome do usuário que logou no sistema

                $stmt = $pdo->prepare("SELECT u_nome AS nome FROM cms_usuarios WHERE u_email = '$email'");
                $stmt->execute();

                $linha = $stmt->fetch(PDO::FETCH_ASSOC);

                $nome = $linha['nome'];
                $_SESSION['nome'] = $nome;
                $_SESSION['logged_in'] = true;
                echo $_SESSION['nome'];

                header('Location: pages/system.php');
                exit();

            } else {
                $error = 'Email ou senha incorretos!';
            }
        }

    }

    ?>

The page system.php remained the same, unchanged.

  • Now it’s better, but I still think 2 querys are unnecessary

  • I’m kind of new at this. Running 2 querys would have a worse performance? Or does not change much in performance?

  • Of course, there are two queries to return what you can do in a query.

Browser other questions tagged

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