I’m pretty new to both PDO and OOP. I’m trying to write a class that connects to a database and updates inserts and modifies it. I have several questions:
-
Is it good practices to connect to the database in the constructor?
-
Should the one class be updating, inserting, modifying and connecting or should it be split up into several classes?
-
Why is runQuery not working? I assume its because $pdo is defined in a different scope. How would I get this working?
-
If the class is include at the top of every page does that mean it will reconnect to the database every time a new page is loaded and will that cause security issues?
Apologies for the overload of questions. Thanks in advance for any answers.
<?php
class Login{
private $_username;
private $_password;
private $_host;
private $_database;
private $_driver;
//Connect to the database
function __construct($configFile){
$connectionDetails = parse_ini_file($configFile);
$this->_username = $connectionDetails['username'];
$this->_password = $connectionDetails['password'];
$this->_host = $connectionDetails['host'];
$this->_database = $connectionDetails['database'];
$this->_driver = $connectionDetails['driver'];
$pdo = new PDO("$this->_driver:host=$this->_host;dbname=$this->_database", $this->_username, $this->_password);
}
public function loginAllowed($user, $pw){
$sth = $pdo->setFetchMode(PDO::FETCH_ASSOC);
print_r($sth);
}
public function runQuery($query, $params){
$sth = $this->pdo->prepare($query);
$sth->execute($params);
}
}
Because
$pdois a local variable in your constructor and your methodloginAllowed. You should make it an instance variable (private $pdo) so you can call it through$this->pdo. I also suggest to use type hinting here, give thePDOclass as a parameter in the constructor.Example
You shouldn’t bother your class with reading settings and initialising your database connection (definitely read about separation of concerns), keep it out of your class. Just give the PDO object as a parameter (I used type hinting, that way you are forced to provide an object of the
PDOtype). Another advantage is that you can now make sure you have only one active database connection (you can manage this in your code base), creating multiple connections is unnecessary and definitely unwanted (performance wise).Also use require_once to include your class definition. Otherwise you will get many errors about redeclaring (and you’d want to avoid that).