试图解决mysqli_real_escape_string错误

时间:2014-02-07 22:56:58

标签: php mysqli

我尝试使用此函数停止SQL_injection。但我想知道为什么会出现这个错误?

define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'cms');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }
mysqli_query($link, "SET NAMES 'utf8';");

function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
    $str = stripslashes($str);
}
return mysqli_real_escape_string($link, $str);
}

$SmjestajGPS = clean( $_POST['SmjestajGPS'] );

我收到了这个错误:

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /home/ninpriva/public_html/admin/smjestaj-obrada.php on line 17
OK

但是当我走这条路时,我没有错误:

$SmjestajGPS = mysqli_real_escape_string($link, $_POST['SmjestajGPS'] );

1 个答案:

答案 0 :(得分:0)

应该重写干净,如下所示:

function clean($link, $str) {
    $str = trim($str);
    if (get_magic_quotes_gpc()) {
       $str = stripslashes($str);
    }
    return mysqli_real_escape_string($link, $str);
}

$SmjestajGPS = clean($link, $_POST['SmjestajGPS']);