Call to a member function real_escape_string() on a non-object
I'm getting this error:
Call to a member function real_escape_string() on a non-object
and here's $db
$db = new mysqli("127.0.0.1", "username", "password", "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 ses开发者_StackOverflow社区sionid='$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
?
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.
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.
If you are initializing $db
somewhere, make sure it's before readSession
is called. Also check for an error message when you make the connection. It returns false
on error, which is not an object.
from the PHP manual, you should using one of these error checking methods to ensure the connection is established successfully:
/*
* 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());
}
There is also a global function that doesnt require a db reference.
$sessionId = mysql_real_escape_string($sessionId);
http://php.net/mysql_real_escape_string
精彩评论