使用 MySQLi 时调用非对象上的成员函数 real_escape_string()


Call to a member function real_escape_string() on a non-object when using MySQLi

我已经尝试了有关此主题的其他问题发布的所有解决方案,但没有一个有效。

如果这是一个基本问题,我很抱歉,但我是 MySQLi 的新手,我无法弄清楚为什么这种连接不起作用。

我的函数.php文件中有一个函数,它有:

function cleanInput($string) {
    $stripsql = $connect->real_escape_string($string);
    $addslashes = addslashes($stripsql);
    return $addslashes;
}

第二行是在标题中抛出该错误。

我确实连接到数据库,$connect是一个工作变量。它是在配置中设置的.php使用以下方法:

$connect = new mysqli('localhost', 'shop', 'password', 'zen');

我什至尝试在函数之前移动该行无济于事。

函数.php文件中$connectvar_dump不返回 NULL,它返回有关数据库的数据,从 object(mysqli)#1 (19) { ["affected_rows"]=> int(0) 开始,然后继续处理大量行。

目前,$connect超出范围,只需将其添加到参数中:

$connect = new mysqli('localhost', 'shop', 'password', 'zen');
function cleanInput($connect, $string = '') {
    if(!empty($string)) {
        $stripsql = $connect->real_escape_string($string);
        return $stripsql;
    }
}
$my_string = 'your string here';
$escaped_string = cleanInput($connect, $my_string);

旁注:或者,如果可以,您也可以使用预准备语句。