Empty function return

Asked

Viewed 606 times

2

Could someone tell me why my insert2 function is returning null after insertion? she should be returning the string with the success message.

<?php
require_once 'conexao.php';
$con = new Conexao();

function insert($dados, $tabela, $campo_unico) : string{

    global $con;

    //Verifica se tem algum campo que tenha que ser único no BD
    if(is_null($campo_unico)) { 
        insert2($dados, $tabela);
    }else{ //Caso tenha verifica se já existe algum registro
        $sql = "SELECT * FROM ".$tabela." WHERE ".$campo_unico."=:".$campo_unico;
        $select = $con->conectar()->prepare($sql);

        if(is_numeric($dados[$campo_unico])){
            $select->bindValue(":".$campo_unico, $dados[$campo_unico], PDO::PARAM_INT);
        }else {
             $select->bindValue(":".$campo_unico, $dados[$campo_unico], PDO::PARAM_STR);
        }
        $select->execute();

        if( ($select->rowCount()) > 0) {
            return "O ".$campo_unico." informado já existe em nossos registros";
        }else {
            insert2($dados, $tabela);
        }

    }

}

function insert2($dados, $tabela) : string{
        global $con;

        $i = 0;
        $sql = "INSERT INTO " . $tabela . " (";
        foreach ($dados as $key => $valor) {
             if ($i == count($dados)-1) {
                $sql .= " ".$key." ";
            } else {
                $sql .= " ".$key.", ";
            }
            $i++;
        }
        $sql .= ")";
        $sql .= " values (";

        $i = 0;
        foreach ($dados as $key => $valor) {
             if ($i == count($dados)-1) {
                $sql .= " :".$key." ";
            } else {
                $sql .= " :".$key.", ";
            }
            $i++;
        }
        $sql .= ")";

        $insert = $con->conectar()->prepare($sql);
        foreach ($dados as $key => $valor) {
            if (is_numeric($valor)) {
                $insert->bindValue(":$key", $valor, PDO::PARAM_INT);
            } else {
                $insert->bindValue(":$key", $valor, PDO::PARAM_STR);
            }
        }
        if ($insert->execute()) {
            return "Registro inserido com sucesso";
        } else {
            return $insert->errorInfo();
        }
}

The mistake you’re making is this:

Fatal error: Uncaught Typeerror: Return value of Insert() must be of the type string, None returned in ...:34

Which is precisely why the return of the function is being null Stack trace:

  • 1

    It is easier to debug this code to find the cause of the error (line and message). For CRUD type operation I do not recommend you have return with success message or error; you will not know what is what. Return a bool flag or the last ID when it is Insert and in case of error use the exceptions adequately.

  • 1

    I’ve never seen it, wear it : at the end of a function, you can indicate me a link where I can have more details of this ?

  • 1

    @Leandrolima in php7 you can specify the function return type.

  • Papa the error you are having is this: Fatal error: Uncaught Typeerror: Return value of Insert() must be of the type string, None returned in ... which is precisely why it is returning empty. Leandro Lima, these are new features of php 7 that allows you to choose the return type of the function, from a look ai : https://tableless.com.br/10-novidades-do-php-7/

  • @rray I also did not know, in which case would error if the function played a exception?

  • 1

    you always call insert()? see that in this function has a call from insert2($dados, $tabela); and you don’t get the result.

  • 1

    Change insert2($dados, $tabela) for: return insert2($dados, $tabela)

  • 1

    @guillermoscimento I think this only applies to php7 (forward) it seems to me important to keep the tag.

Show 3 more comments

2 answers

3

If I understand the code, I believe that there is a lack of a:

if( ($select->rowCount()) > 0) {
    return "O ".$campo_unico." informado já existe em nossos registros";
}else {
    insert2($dados, $tabela);
}

Should be:

if( ($select->rowCount()) > 0) {
    return "O ".$campo_unico." informado já existe em nossos registros";
}else {
    return insert2($dados, $tabela); //Faltava o return
}

2


In typed languages it is quite common to specify the type of return of a method and it must obey this specification otherwise the compiler issues an error. In PHP7 works the same way or almost.

See that in insert() there is only one Return, there should be at least two. I left only the function skeleton to highlight the problem.

function insert($dados, $tabela, $campo_unico) : string{ //obriga a função retorna o tipo
    global $con;
    if(is_null($campo_unico)) {

    }else{ //Caso tenha verifica se já existe algum registro
        if(is_numeric($dados[$campo_unico])){

        }else {

        }
        $select->execute();

        if( ($select->rowCount()) > 0) {
            return "O ".$campo_unico." informado já existe em nossos registros";
        }else {
            insert2($dados, $tabela);
        }

    }
   //caso o código chegue aqui não existe nenhum return para satisfazer a assinatura do método.
}

By calling insert() in case of failure errorInfo(); returns an array or it will be necessary a treatment to convert it into string, not just give a return insert2($dados, $tabela); That also violates the signature.

insert2() suffers from the same problem see:

function insert2($dados, $tabela) : string{
 //código....

    if ($insert->execute()) {
        return "Registro inserido com sucesso";
    } else {
        return $insert->errorInfo(); //retorna um array o que quebra a assinatura
    }
 }

To solve the first step is to return the expected type, do not return errorInfo() but a

return implode(' - ', $insert->errorInfo());

Related:

PHP 7 has argument typing and return, but is optional. This is good or bad?

Typing the return in PHP 7. What are the advantages?

  • 1

    Should be return insert2($dados, $tabela)

  • @Papacharlie no :P edited the answer (now) with the details.

  • 1

    Truth, the array of errorInfo kills typing. If you serialize the error message we will have (string) success, and (string) error. [fuuu rs]. The insert2 function could remove the typing and play a exception for previous function treat this error.

  • 1

    @Papacharlie this, if there is a rule (return typing) need to follow it. It gives to use a implode() and return the expected ... exceptions used in the wrong way is even worse =.

  • Thank you all, I solved the problem by putting the Return as indicated, and not to violate the signature of the function I put to return the position of the errorInfo() array that contains the warning message: $error = $Insert->errorInfo(); Return $error[2];

Browser other questions tagged

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