Call to a member function real_escape_string() on

2020-03-31 03:19发布

问题:

I have tried every solution posted on other questions about this topic, but none of them work.

I'm sorry if this is a basic question, but I'm new with MySQLi and I can't figure out why this connection won't work.

I have a function in my functions.php file that has:

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

The second line is throwing that error in the title.

I do connect to the database, and $connect is a working variable. It's set in config.php using:

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

I've even tried moving that line right before the function to no avail.

A var_dump on $connect in the functions.php file does not return NULL, it returns data about the database starting with object(mysqli)#1 (19) { ["affected_rows"]=> int(0), and then continuing with lots of rows.

回答1:

Currently, $connect is out of scope, just add it in the parameter:

$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);

Sidenote: Or if you can, you can also use prepared statements.



标签: php mysql mysqli