Kumar Kumar - 5 months ago 28
PHP Question

Error after executing mysqli_query in some user defined function

Content of getUserName.php file with one method getField:

<?php
function getfield($field)
{
if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id']))
{
$query="SELECT `$field` FROM `user` WHERE `id`='".$_SESSION['user_id']."'";
if($query_run=mysqli_query($conn,$query))
{
if($query_result=mysqli_fetch_field($query_run))
{
return $query_result;
}
} else {
printf("error: %s\n", mysqli_error($conn));
}
}
?>


Content of index.php that includes connection.php that holds $conn object & getUserName.php:

<?php
include_once('connection.php');
include_once('function.php');
$fname=getfield('Fname');
$lname=getfield('Lname');

echo $name=$fname.' '.$lname;
?>


After executing it, I got an error message like:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/confessi/public_html/college/profile/function.php on line 8


Any idea? Why am I getting the error? Any help would be appreciated. Thanks in advance.

Answer

Variable $conn is not available in your getfield function's scope.

Declaring it global inside the function should do the trick:

<?php
function getfield($field)
{
    global $conn;

    if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id']))
    {
        $query="SELECT `$field` FROM `user` WHERE `id`='".$_SESSION['user_id']."'";
        if($query_run=mysqli_query($conn,$query))
        {
            if($query_result=mysqli_fetch_field($query_run))
            {
                return $query_result;
            }
        }
        else
        {
            printf("error: %s\n", mysqli_error($conn));
        }       
    }  
}
?>
Comments