php - PDO connection object not passing to a class -
ok, 2 separate php files, 1 main script, other class. i'm trying connect sql database pdo. create pdo connection in main script, pass class in other script, queries made. however, getting following error :
fatal error: call member function prepare() on non-object in /applications/xampp/xamppfiles/htdocs/test/class.php on line 16
my understanding php pass references objects across scripts, error says object not exist.
below main php script, creates pdo object , passes class played with.
<?php session_start(); unset($_session['reference']); require('class.php'); //connect database, know username , password not included $dsn = 'mysql:dbname=test;host=localhost'; try { $dbh = new pdo($dsn); $dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception); } catch (pdoexception $e) { die ( 'connection failed: ' . $e->getmessage() ); } $objreference = new reference($dbh); $reference = $objreference->getreference(); $_session['reference'] = $reference; session_write_close(); ?>
below class.php file. receives object , data.
<?php class reference { private $reference; private $dbh; public function __construct($dbh) { $this->dbh=$dbh; $this->setreference(); } private function setreference() { $refid=$dbh->prepare(" select max(id) createx "); $refid->execute(); $id = $refid->fetchcolumn(); $id=$id+1; $this->reference = $id; } public function getreference() { return $this->reference; } } ?>
is there way pass pdo objects classes not aware of? all.
since $dbh
instance variable, in setreference
function should using pseudo $this
reference it:
$refid=$this->dbh->prepare(" select max(id) createx ");
i.e. use $this->dbh
.
Comments
Post a Comment