Handling and Error Handling

Asked

Viewed 141 times

2

I want to know how the error handling should be done, correctly, for a non-compulsory variable, since if it is not informed, a Fatal Error - Undefined Index.

Context:

Through my system I register a publication (documents for the user to view), and create a folder system for the user to access the data later.

Problem:

When a publisher will register the publication, he can inform all fields or some (in case my question is specifically, about the fields fk_empregado and mes ), that when there is a data register and is not informed fk_empregado or the field mes it generates the following Notice:

Notice: Undefined index: fk_empregado in ... on line 14 //Linha que recebe através de POST os dados do campo empregado
Notice: Undefined index: mes in ... on line 19 //Linha que recebe através de POST os dados do campo mes

So here’s my question, exactly as I can inform the script that there is no problem these two fields are undefined, and that it can continue normally(I don’t know the answer, but I’m sure it’s not with the @)?

Code of the Insert Page :

    $fk_titulo = $_POST['publicacao'];
    $fk_tipo = $_POST['tipo_publicacao'];
    $fk_empregado = $_POST['empregado'];  
    $fk_empresa = $_POST['empresa_destino'];
    $data_vencimento = $_POST['data_vencimento'];
    $data_pagamento = $_POST['data_pagamento'];
    $arqName = $_FILES['arquivo']['name']; 
    $mes = $_POST['mes'];
    $ano = $_POST['ano'];
    $valor = $_POST['valor'];
    $publicante = $_SESSION['nome'];
    $observacao = $_POST['observacao'];
    $status = "N";

    $dir = 'upload/publicacoes/' . implode('/', array_filter([$fk_empresa, $fk_tipo, $fk_titulo, $fk_empregado, $ano, $mes]))."/";
  • You can send them without having any value, so I think there is no error (I do not know very well the behavior of PHP)

  • When they are received empty a Notice Undefined Index is generated

2 answers

3


The first point is do you really need these assignments? can’t use the $_POST direct? If you can’t the two best ways to test the existence of a key are.

1) isset()/empty() plus the use of the ternary

Basically the isset()/empty() verify the existence (according to its criteria) if yes $idade receives the value of the container array receives a default value, in case 99.

$arr = array('nome' => 'abc', 'email' => '[email protected]');
$idade = !isset($arr['idade']) ? $arr['idade'] : 99;

2) Use of the null coalescing operator (??) available only on PHP7.

It checks if the key exists if it does the assignment with the respective value or otherwise the default value.

$idade = $arr['idade'] ?? 99;
  • What do you mean, direct post? I’m kind of new and always learned that way that’s in the question, and yes I do if the field is typed if not, I don’t need to be with an empty variable

  • 1

    @Sauldasilvarolim depending on the case can move forward (functions/call) the $_POST no need to create a new variable. Ex: validaCPF($_POST['cpf']); or as: validaCPF(isset($_POST['cpf']) ? $_POST['cpf'] : 'valor padrão');

2

Something really practical and recommended is to make use of ternary operators along with the functions isset and empty as in @rray’s reply, to prevent the reading of non-existent indexes.

Something I also like to use when I need variables with the same name as the index assigned in the form (or even because of long forms), and at the same time avoid mistakes like this (Undefined index) is iterating the variable $_POST by full and delete the values I don’t need.

# valores em $_POST, provenientes do formulário
Array ( [nome] => edilson [apelido] => samuel [email] => [enviar] => enviar )

if(isset($_POST)){
    foreach(array_keys($_POST) as $input)
    {
        switch($input):
            case 'enviar':
            case 'outro':
                unset($_POST[$input]);
                continue;
            default:
                ${$input} = $_POST[$input];
                print "${$input} : $input <br>";
                break;
        endswitch;  

    }
    if($email){
        print "<br>email definido<br>";
    } else {
        print "<br>email não definido<br>";
    }
}

In the case of filters, it applies directly to ${$input}, which results in something like this:

${$input} = validar($_POST[$input]);

Browser other questions tagged

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