I’m attempting to make a simple query library and I’m using PDO for database access.
Let’s say I have the following two classes:
class FirstClass {
var $dbh;
function __construct($host,$dbname,$user,$pw) {
$this->dbh = new PDO ("mysql:host=$host;dbname=$dbname",$user,$pw);
}
function use_second($foo) {
return new SecondClass ($foo,$this->dbh);
}
}
class SecondClass {
function __construct($foo, $dbh) {
$sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
$sth = $sth->execute(array('foo'=>$foo));
// do something with the query
}
}
Is this the correct way to use the same PDO connection between classes? – Because I seem to be having some issues with this, for example, if I var_dump my connection from the second class, I get:
object(PDO)#2 (0) { }
Surely that isn’t right?
Also if I run a select query, and then dump the $sth variable, I just get:
bool(true)
Is this because I am handling the connection incorrectly? – If so how can I properly use the same connection between classes?
This happens, because you overwrite
$sth, which was your statement, but now is a boolean:To correct it, just do not overwrite
$sth, so you are able to fetch results from it: