Using method from another function to create a unique dbQuery to perform a prepare statement
I'm having some trouble with using a method from a different function. They are both in the same class, but I keep getting the error "Fatal error: Call to a member function prepare() on a non-object in / / blabla.php on line 42"
The code I've written looks like this now:
public function connectDatabase()
{
开发者_StackOverflow中文版 try {
$DBC = new PDO("mysql:host=".self::dbhost.";dbname=".self::dbname."", self::dbuser, self::dbpass);
$DBC->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
public function InsertNewForumData( $data )
{
$new = $DBC->prepare( $data );
$new->execute();
}
The reason you are getting this error is because $DBC is undefined in your InsertNewForumData
method. You can either pass it by reference by doing self::InsertNewForumData( $data, $DBC );
and also add it to the parameter list of that method's declaration or else save it to self::DBC
like this:
public function connectDatabase()
{
try {
self::DBC = new PDO("mysql:host=".self::dbhost.";dbname=".self::dbname."", self::dbuser, self::dbpass);
self::DBC->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
public function InsertNewForumData( $data )
{
$new = self::DBC->prepare( $data );
$new->execute();
}
精彩评论