Handling and Error Handling

2

I want to know how to correctly handle the error handling for a non-mandatory variable, since if it is not informed, a Fatal Error - Undefined Index is generated.

Context :

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

Problem :

When a publisher is going to register the publication, it can inform all the fields or some (in this case my question is specifically about the fields fk_empregado and mes ), that when there is the data register and it is not fk_empregado or the mes field 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, my question is, Exactly how can I tell the script that there is no problem these two fields are undefined, and that it can continue normally (I do not know the answer, but I'm sure not is with @ )?

Page Code InsertPublication.php:

    $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]))."/";
    
asked by anonymous 07.04.2017 / 22:23

2 answers

3

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

1) isset() / empty() plus ternary usage

Basically, isset()/empty() checks for existence (according to its criteria) if $idade receives the value of the array of the counter it 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 in PHP7.

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

$idade = $arr['idade'] ?? 99;
    
07.04.2017 / 22:42
2

Something really practical and recommended is to make use of ternary operators along with the isset and empty functions as in the @rray response, to avoid reading indexes that do not exist.

Something I also like to use when I need variables with the same index name assigned in the form (or even because of large forms) , and at the same time avoid errors like this (undefined index) is iterating the variable $_POST by integer and deleting the values that I do not 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 case of filters, it applies directly to ${$input} , which results in something like this:

${$input} = validar($_POST[$input]);
    
08.04.2017 / 17:14