2013-07-05 52 views
-2

我已经看过这么多人有这个相同的问题,但没有解决方案是相关/他们没有工作。完全失去了与mysqli_real_escape_string

首先,这里是我的简单的代码让一切变得简单:

<?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"); 
?> 

这将导致错误:

Fatal error: Call to a member function real_escape_string() on a non-object on line 13

我感觉真的很愚蠢,激怒现在..谁能帮我?

编辑:我试图从功能删除所有其他行,因此,所有它做的是mysqli的世外桃源,仍然没有。我也试图通过$string = new stdClass();在功能上的第一行定义$字符串,但仍然没有任何结果。

+3

这是一个范围问题;你的'$ mysqli'对象不在你的函数中。 – andrewsi

+0

它不在范围内? :/它保持开放,当然我不需要在使用资源的每个函数中重新定义一个mysqli连接? – Chuckun

+2

不,但您需要将它传递给函数。处理这个问题的更好方法是使用一个类,其中每个函数都可以使用连接作为对象属性。 – deceze

回答

2

$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"); 
?> 
+0

太好了,非常感谢..我不确定这会实用,因为我在整个工作中使用mysqli_secure很多(以前是mysql_secure,之前是oop),并且需要大量编辑,所以也许我将不得不弄清楚如何让数据库在任何函数中都可用。 – Chuckun

+0

@Chuckun,不幸的是我现在没有时间了,但我保证更新我的答案,向您展示一个具有mysql函数的策略孤立的,但也广泛使用初始化连接。 – ElmoVanKielmo

+0

在你的函数里面添加'global $ mysqli'然后如果你不想在你的项目的任何地方更新你的调用函数 – Dave