Reputation: 55
Ok, 2 separate php files, one is the main script, the other is the class. I'm trying to connect to a sql database with PDO. I create the PDO connection in the main script, then pass it to a class in the other script, where queries are made. However, I am getting the following error :
Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/test/class.php on line 16
My understanding was that PHP could pass references to objects across scripts, but the error says the object does not exist.
Below is the main php script, creates the PDO object and passes to a class to be played with.
<?php
session_start();
unset($_SESSION['reference']);
require('class.php');
//connect to database, I know that username and password are 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 is the class.php file. Receives the object and get 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) FROM createX ");
$refid->execute();
$id = $refid->fetchColumn();
$id=$id+1;
$this->reference = $id;
}
public function getReference() {
return $this->reference;
}
}
?>
Is there another way to pass PDO objects to classes that I am not aware of? Thanks all.
Upvotes: 2
Views: 1135
Reputation: 4923
The reason you're getting that error is that your DB connection is failing. It looks like you're forgetting to pass the password parameter when you attempt to instantiate the PDO object.
if you temporarily comment out the try / catch block you will get a more detailed error message which will likely prove this to be the case.
When you get your DB connection sorted out, I would do the following:
It's much simple and it's more secure, but first sort out your DB connection issue.
Upvotes: 0
Reputation: 38645
Since $dbh
is an instance variable, in your setReference
function you should be using the pseudo $this
to reference it:
$refid=$this->dbh->prepare(" SELECT MAX(id) FROM createX ");
i.e. use $this->dbh
.
Upvotes: 2