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?
The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning null to the variable that holds the object.
PDO refers to PHP Data Object, which is a PHP extension that defines a lightweight and consistent interface for accessing a database in PHP. It is a set of PHP extensions which provide a core PDO class and database-specific driver.
$DBH = null; You can get more information on database-specific options and/or connection strings for other databases from PHP.net.
This happens, because you overwrite $sth
, which was your statement, but now is a boolean:
class SecondClass {
function __construct($foo, $dbh) {
// returns PDOStatement:
$sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
// returns boolean:
$sth = $sth->execute(array('foo'=>$foo));
// do something with the query
}
}
To correct it, just do not overwrite $sth
, so you are able to fetch results from it:
class SecondClass {
function __construct($foo, $dbh) {
// returns PDOStatement:
$sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
// returns boolean:
$success = $sth->execute(array('foo'=>$foo));
// do something with the query
if ($success) {
// do something with $sth->fetchAll() or $sth->fetch(), or anything
$all_the_results = $sth->fetchAll();
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With