Wednesday, May 2, 2012

PHP PDO class construction

Im pretty new to both PDO and OOP. Im trying to write a class that connects to a database and updates inserts and modifies it. I have several questions.

1) Is it good practices to connect to the database in the constructor?

2) Should the one class be updating, inserting, modifying and connecting or should it be split up into several classes?

3) Why is runQuery not working? I assume its because $pdo is defined in a different scope. How would I get this working?

4) 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.

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);

public function runQuery($query, $params){
$sth = $this->pdo->prepare($query);


No comments:

Post a Comment