Andre Chenier
Andre Chenier

Reputation: 1186

php user-defined-function parameter scope assignment issue

after php code row 1 and 2, I got a notice and error message.

Notice: Undefined variable: dbc in ...
Warning: mysqli_get_host_info() expects parameter 1 to be mysqli, null given in ...

connectdb();
echo mysqli_get_host_info($dbc);

Can you help me please to solve my notice & warning?

How can I make $dbc defined also for outher functions? I am working with error level -1 by the time being. please don't tell not to display the notices as a solution. Unfortunately, I can't understand the custom function variable passage issues. thanks.

function connectdb() 
{
    $dbc = mysqli_connect (db_host, db_user, db_password, db_name);
    if (!$dbc) 
        {
            $txt = mysqli_connect_errno().mysqli_connect_error();
            db_connect_error_mail($txt);
            unset ($txt);
            die('error message.');
        } 
    else 
        {
            return $dbc;
        }
}

Upvotes: 0

Views: 160

Answers (2)

Achrome
Achrome

Reputation: 7821

Think, you are returning $dbc, from the function, but you are not assigning the return value of the connectdb() function in line 1. How will the compiler know that you saved the return value in $dbc?

$dbc = connectdb();

This will fix your error.

Upvotes: 1

leftclickben
leftclickben

Reputation: 4614

You aren't assigning the return value of connectdb() method anywhere. You want:

$connection = connectdb();
echo mysqli_get_host_info($connection);

For clarity I have used a different variable name as the one you use in your function, because they are different variables, as they are defined in different scopes.

Upvotes: 2

Related Questions