Local and global variable difficulty - PHP

Asked

Viewed 33 times

1

I’m having trouble understanding how to use the value of a local variable in another statement:

I am using this concept in the following code :

<?php
if(isset($_GET["email_cad"])){
    //quero usar a var $email_cad
    $email_cad = $_GET["email_cad"];
    if(!empty($email_cad)){
        $sql = "SELECT email_cad FROM part_user WHERE email_cad = '$email_cad' ";
        }else {
            echo "Insira um email";
            return;
        }
        $result = mysqli_query($con, $sql);
        $linha = mysqli_fetch_assoc($result);
            if($linha['email_cad'] == $email_cad ){        
                echo $email_cad;

             }else {
                echo "Email inválido !";
             }  
}

if(isset($_GET["senha_cad"])){
    $senha_cad = $_GET["senha_cad"];
    if(!empty($senha_cad)){
        //Aqui estou recebendo o erro onde $email_cad é indefinida
        $sql = "SELECT senha_cad FROM part_user WHERE email_cad = '$email_cad' ";
        }else {
            echo "Insira uma senha";
            return;
        }
        $result = mysqli_query($con, $sql);
        $linha = mysqli_fetch_assoc($result);
            if($linha['senha_cad'] == $senha_cad ){        
                echo $senha_cad;
             }else {
                echo "Senha inválida !";
             }  
}
?>

My question is, how to use the variable $email_cadwith the same value in both statements ? Because the way it is, an error is returned : Undefined index: email_cad, for use in the second declaration. How should I proceed?

  • Why not do it all in one statement? The if(!empty(...) is unnecessary because you use the isset.

  • @zekk understand that I can do in other ways and thank you for the attention, however doubt and learning, would be even on how to use the value of the variable of the 1st statement in the 2nd.

1 answer

1


You can declare the variable outside the if:

$email_cad = $_GET["email_cad"];

if(!empty($email_cad)){
    $sql = "SELECT email_cad FROM part_user WHERE email_cad = '$email_cad' ";
}else {
    echo "Insira um email";
    return;
}

$result = mysqli_query($con, $sql);
$linha = mysqli_fetch_assoc($result);
if($linha['email_cad'] == $email_cad ){
    echo $email_cad;
}else {
    echo "Email inválido !";
} 
// Resto do código...

Browser other questions tagged

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