Question

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;
} 
Was it helpful?

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.

OTHER TIPS

the $db variable is not in scope in safe(). Try:

$username = safe($db, stripslashes(trim($_POST['username'])));

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

   return $secureString;
} 

Or perhaps cleaner:

function safe($db, $value)
{
    $secureString = $db->real_escape_string($value);

   return $secureString;
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top