【问题标题】:Call to a member function real_escape_string() on a non-object when using MySQLi使用 MySQLi 时在非对象上调用成员函数 real_escape_string()
【发布时间】:2015-03-13 03:03:20
【问题描述】:

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

如果这是一个基本问题,我很抱歉,但我是 MySQLi 的新手,我不知道为什么这个连接不起作用。

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

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

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

我确实连接到数据库,$connect 是一个工作变量。它在 config.php 中使用:

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

我什至尝试在函数之前移动那条线,但无济于事。

functions.php 文件中$connect 上的var_dump 不返回NULL,它返回有关数据库的数据,以object(mysqli)#1 (19) { ["affected_rows"]=> int(0) 开头,然后继续很多行。

【问题讨论】:

  • 是的,范围问题。在功能上不错,全局不太好,并且被许多现代开发者所反对。

标签: php mysql mysqli


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 2013-09-26
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多