Insert attempt before error (PHP)

Asked

Viewed 31 times

2

I have a student enrollment system in a college system.

Part of the code showing the error or not:

        while (($matricula = fgets($handle, 1024)) !== false) {
            $cont++;
            erro("Lendo matricula $cont de $qtde_matriculas");
            $matricula = trim($matricula);
            if(!is_numeric(trim(substr($matricula,0,5)))){
                erro("matricula $cont invalido [$matricula]");
            }else{
                $arrayReturn = buscarnafaculdade( $matricula );
                if($arrayReturn['status'] == "ERROR" || $arrayReturn == false){
                    erro(" ERRO servidor faculdade para inserir matricula [$matricula]");
                    $result = print_r($arrayReturn);
                    erro($result);
                }else{
                    erro("matricula [$matricula] inserido no no sistema!");
                }
            }
            $matricula = null;

Turns out, if error occurs I jump to the next one. I’d like to change it.

I would like a certain number of attempts to be made and if I continue to make the mistake in:

if($arrayReturn['status'] == "ERROR" || $arrayReturn == false){
                    erro(" ERRO servidor faculdade para inserir matricula [$matricula]"); 

Then it would stop.

It is possible?

1 answer

2


In a "manual" way you can implement as follows:

$NUM_OF_ATTEMPTS = 5;
$attempts = 0;

while (($matricula = fgets($handle, 1024)) !== false) {
    $cont++;
    erro("Lendo matricula $cont de $qtde_matriculas");
    $matricula = trim($matricula);

    if(!is_numeric(trim(substr($matricula,0,5)))){
        erro("matricula $cont invalido [$matricula]");
    }else{
        do{
            $arrayReturn = buscarnafaculdade( $matricula );
            if($arrayReturn['status'] == "ERROR" || $arrayReturn == false){
                $attempts++;

                if ($attempts <= $NUM_OF_ATTEMPTS){
                    continue;
                }

                erro(" ERRO servidor faculdade para inserir matricula [$matricula]");
                $result = print_r($arrayReturn);
                erro($result);
            }else{
                erro("matricula [$matricula] inserido no no sistema!");
                $attempts = $NUM_OF_ATTEMPTS;
            }
        }while($attempts < $NUM_OF_ATTEMPTS);       

        $attempts = 0;
    }
}

$matricula = null;      

I didn’t test the code to see if there is any syntax error but the idea would be this.

  • Thank you! It worked!

Browser other questions tagged

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