Search code examples
phpmysqlfunctionmysqlimysql-real-escape-string

PHP Mysqli_real_escape_string in function expects parameter to be 1. Null given


I have a mysql function to escape strings. I continue to be plagued with a never ending error. The feed spits out:

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /home/shipstud/public_html/post_auth.php on line 39.

Any ideas on how to fix this would be appreciated. I've attached the relevant code below:

//connect to server and database
$db=mysqli_connect('***','***','***','***');

// check connection
if (mysqli_connect_errno()) {
    echo "Connect failed";
    exit();
}



//parameter checking
$username = safe(stripslashes(trim($_POST['username'])));


//sanitize input parameters
function safe($value)
{
    $secureString = mysqli_real_escape_string($db, $value);

   return $secureString;
} 

Solution

  • You haven't imported the $db variable into the function's scope.

    function safe($value)
    {
       global $db;
    
       $secureString = mysqli_real_escape_string($db, $value);
    
       return $secureString;
    }
    

    Alternatively, you can pass in the variable as an argument.