php 在非对象上调用成员函数 real_escape_string()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6418856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call to a member function real_escape_string() on a non-object
提问by bear
I'm getting this error:
我收到此错误:
Call to a member function real_escape_string() on a non-object
在非对象上调用成员函数 real_escape_string()
and here's $db
这是 $db
$db = new mysqli("127.0.0.1", "username", "password", "sch5400");
$db = new mysqli("127.0.0.1", "用户名", "密码", "sch5400");
in code:
在代码中:
function readSession($sessionId) {
global $db;
$sessionId = session_id();
// escape session ID
$sessionId = $db->real_escape_string($sessionId);
$time = time();
$result = $db->query("SELECT sessiondata FROM sessions WHERE sessionid='$sessionId' AND expiry > $time");
if ($result->num_rows > 0) {
$row = $result->fetchRow();
return $row['sessiondata'];
}
// return empty string
return "";
}
It appears on line 5, relative to code above. Didn't I instantiate $db
?
它出现在第 5 行,相对于上面的代码。我没有实例化$db
吗?
回答by zerkms
Probably the better solution would be to create a singleton function:
可能更好的解决方案是创建一个单例函数:
function get_my_db()
{
static $db;
if (!$db) {
$db = new mysqli("127.0.0.1", "username", "password", "sch5400");
}
return $db;
}
and use it like
并像使用它一样
$db = get_my_db();
in every function that needs db instance.
在每个需要 db 实例的函数中。
回答by Brad Mace
You haven't initialized $db
anywhere in the code that's shown, and from the error it sounds like it hasn't been initialized anywhere else (yet) either.
您还没有$db
在显示的代码中的任何地方初始化,从错误来看,它似乎也没有在其他任何地方(尚未)初始化。
If you are initializing $db
somewhere, make sure it's beforereadSession
is called. Also check for an error message when you make the connection. It returns false
on error, which is not an object.
如果您正在$db
某处初始化,请确保它在readSession
被调用之前。建立连接时还要检查错误消息。它返回false
错误,它不是一个对象。
from the PHP manual, you should using one of these error checking methods to ensure the connection is established successfully:
从 PHP 手册中,您应该使用以下错误检查方法之一来确保成功建立连接:
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
回答by Craig White
There is also a global function that doesnt require a db reference.
还有一个不需要数据库引用的全局函数。
$sessionId = mysql_real_escape_string($sessionId);