Is it possible to maintain PDO connections between classes?

I am trying to create a simple query library and I am using PDO to access the database.

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 right way to use the same PDO connection between classes? - Since I seem to have some problems with this, for example, if I var_dump my connection to the second class, I get:

 object(PDO)#2 (0) { } 

Is this really wrong?

Also, if I run a select query and then reset the $sth variable, I just get:

 bool(true) 

Is it because I am processing the connection incorrectly? - If so, how can I use the same connection between classes correctly?

+6
source share
3 answers

This happens because you are overwriting $sth , which was your expression, but is now logical:

 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 fix this, just don't overwrite $sth so you can extract the 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(); }; } } 
+3
source

Check out the documentation for PDOStatement :: execute . It returns a boolean value. The fact that sth completes to true means the request succeeded.

Your design is a little shaky because you create objects in non-w770> methods of other objects, which can be confusing. Ideally, all of your objects will be created at the beginning of the controller and added to other objects that need them (for example, a PDO object will be created outside of FirstClass::__construct , and you will have something like __construct(PDO $db) instead of this.

0
source

In your case, I will just ask (asking what I mean, prequalists set) for the finished PDO.

 function __construct($dbh) { $this->dbh = $dbh; } 

This way you get a cleaner approach to what your object needs (it does not need a user / password, etc., it needs a connection to the database!)

It also eliminates the need for an abstraction class (FirstClass), since you can go directly to the second class.

0
source

Source: https://habr.com/ru/post/907033/


All Articles