Difficulty local and global variable - PHP

1

I'm having difficulty understanding how to use the value of a local variable in another declaration:

I'm 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 do I use the $email_cad variable with the same value in both statements? Because of the way it is, an error is returned: Undefined index: email_cad , for use in the second statement. How should I proceed?

    
asked by anonymous 06.08.2016 / 00:47

1 answer

1

You can declare the variable out of 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...
    
06.08.2016 / 01:05