函数中的PHP Mysqli_real_escape_string期望参数为1.空给定

时间:2013-07-07 20:50:12

标签: php mysql function mysqli mysql-real-escape-string

我有一个mysql函数来转义字符串。我继续被一个永无止境的错误所困扰。饲料吐出:

警告:mysqli_real_escape_string()要求参数1为mysqli,在第39行的/home/shipstud/public_html/post_auth.php中给出null。

如何解决这个问题的任何想法将不胜感激。我已附上以下相关代码:

//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;
} 

2 个答案:

答案 0 :(得分:5)

您尚未将$ db变量导入函数scope

function safe($value)
{
   global $db;

   $secureString = mysqli_real_escape_string($db, $value);

   return $secureString;
}

或者,您可以将变量作为参数传递。

答案 1 :(得分:1)

$db变量不在safe()范围内。尝试:

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

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

   return $secureString;
} 

或许更干净:

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

   return $secureString;
}