【问题标题】:Completely lost with mysqli_real_escape_string [duplicate]完全丢失了 mysqli_real_escape_string [重复]
【发布时间】:2023-04-05 06:37:02
【问题描述】:

我见过很多人遇到同样的问题,但没有一个解决方案是相关的/它们不起作用。

首先,这是我的简单代码,让事情变得简单:

<?php
$mysqli = new mysqli("localhost", "root", "", "pembsweb");
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}
function mysqli_secure($string) {
        $string = htmlspecialchars($string);
        $string = trim($string);
        if (get_magic_quotes_gpc()) {
            $string = stripslashes($string);
        }
        $string = $mysqli->real_escape_string($string);
    return $string;
}
echo mysqli_secure("lets\\test//this");
?>

这会导致错误:

致命错误:在第 13 行调用非对象上的成员函数 real_escape_string()

我现在感到非常愚蠢和烦躁..有人可以帮助我吗?

编辑:我尝试从函数中删除所有其他行,所以它所做的只是 mysqli 真正的转义,但仍然没有。我还尝试通过 $string = new stdClass(); 定义 $string函数的第一行,还是什么都没有..

【问题讨论】:

  • 这是范围问题;您的 $mysqli 对象不在您的函数范围内。
  • 怎么不在范围内? :/ 它保持打开状态,当然我不需要在每个使用它的资源的函数中重新定义 mysqli 连接?
  • 否,但您需要将其传递给函数。解决这个问题的更好方法是使用一个类,其中每个函数都可以使用连接作为对象属性。
  • 我明白了,谢谢!我会考虑改变我的方法!
  • @Chuckun - 你在 mysqli connection (正如你所说的在函数中是开放的并且可用的)和 $mysqli object 之间感到困惑 您已声明使用该连接。

标签: php mysql string object escaping


【解决方案1】:

$mysqli 是在其他范围内定义的,而不是您尝试使用它的范围。 将其作为参数传递。

<?php
$mysqli = new mysqli("localhost", "root", "", "pembsweb");
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}
function mysqli_secure($mysqli, $string) {
        $string = htmlspecialchars($string);
        $string = trim($string);
        if (get_magic_quotes_gpc()) {
            $string = stripslashes($string);
        }
        $string = $mysqli->real_escape_string($string);
    return $string;
}
echo mysqli_secure($mysqli, "lets\\test//this");
?>

【讨论】:

  • 太好了,非常感谢.. 我不确定这是否实用,因为我在整个工作中都使用了 mysqli_secure(以前是 mysql_secure,来自 pre-oop)并且需要大量编辑,所以也许我必须弄清楚如何让数据库在任何函数中都可用..
  • @Chuckun,不幸的是我现在没有时间,但我保证会更新我的答案,向您展示一种策略来隔离您的 mysql 功能,但也可以通过初始化连接广泛使用。
  • 在你的函数中添加global $mysqli,那么如果你不想在你的项目中的任何地方更新你对函数的调用
猜你喜欢
  • 2021-01-07
  • 2015-11-07
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-12-10
  • 1970-01-01
  • 2017-04-08
相关资源
最近更新 更多