Error in function - Empty return

Asked

Viewed 101 times

1

This function returns empty.. What’s the bug? Thanks!

$id_pessoa = 1;

function nome_pessoa()
{

$sql = mysqli_query($link, "SELECT * FROM equipe WHERE id='$id_pessoa' ");
while($row = mysqli_fetch_array($sql))
    {
        return $row["nome"];
    }

}   

echo nome_pessoa();
  • 1

    In its function the variables are not defined $link and $id_pessoa, probably by your server settings, these errors were omitted.

  • $link does the connection function. The $id_person I can’t pull from elsewhere? how did I do up there? Declaring as fixed or then for $_POST?

  • @Rodrigomendonça to have access to a variable that is outside the scope of the function, it is necessary to use the global or pass the variable through function parameters, eg: function nome_pessoa($link) { ... } and to call her: echo nome_pessoa($link);

  • Then, I had done the following, and also had an error: $id_pessoa = 1; Function name_person($id_person) { $sql = mysqli_query($link, "SELECT * FROM team WHERE id='$id_person' "); while($Row = mysqli_fetch_array($sql)) { Return $Row["name"]; } echo name_person($id_person); Presented errors: Warning: mysqli_query() expects Parameter 1 to be mysqli, null Given in ... Warning: mysqli_fetch_array() expects expects Parameter 1 to be mysqli_result, null Given in ... Until then I had ctz q would work.. I was lost to solve this.

  • Any suggestion?

1 answer

2

Unlike many other programming languages, variables that are defined in the global scope are not naturally imported into the local scope. Thus, a variable that is defined outside the function will not be defined within the function.

Basically the problem in your code is to use variables that are not defined in the function. You can circumvent this by passing the values by parameter:

function getNomePessoa(mysqli $link, int $id): ?string 
{
    if ($result = $link->query("SELECT * FROM equipe WHERE id='{$id}'")) {
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            return $row["nome"];
        }
    }

    return null;
}

So, just call the function by properly passing the parameters:

$nome = getNomePessoa($link, $id_pessoa);
  • Anderson.. Thank you so much for the explanation.. You’re the man.. I just needed an explanation and an example to better understand how it works, since I’m used to using other forms. Thanks.. This type of help is always very valuable for those seeking to learn.. Again thank you.

Browser other questions tagged

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