I'm fairly new to object oriented programming in php, I just wrote the following script to create a connection using PDO and run a simple Select Query. It works fine, i just need to know if i have done it right! (need to know the best practices i'm missing).
<?php
class Connection
{
protected $host = "localhost";
protected $username = "admin";
protected $password = "admin";
protected $database = "thedatabase";
protected $dsn;
protected $dbh;
protected $opt = array(PDO::ATTR_ERRMODE=> PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE=> PDO::FETCH_ASSOC);
protected $error_found = false;
protected $error_message;
function __construct()
{
$this->dsn = "mysql:host=$this->host;dbname=$this->database;charset=utf8";
try
{
$this->dbh = new PDO($this->dsn, $this->username, $this->password, $this->opt);
}
catch (PDOException $e)
{
$this->error_message = $e->getMessage();
$this->error_found = true;
}
}
public function closeConnection()
{
$this->dbh = null;
}
public function errorsFound()
{
if ($this->error_found == true)
{
return true;
}
else
{
return false;
}
}
public function showError()
{
return $this->error_message;
}
}
class Model extends connection
{
public function select()
{
$sth = $this->dbh->query("SELECT * FROM `users`");
$sth->setFetchMode(PDO::FETCH_ASSOC);
while($row = $sth->fetch())
{
echo $row['username']."
";
echo $row['password']."
";
}
}
}
$connection = new Connection;
if ($connection->errorsFound()==true)
{
$error_messages = "Error: ".$connection->showError();
echo $error_messages;
$connection->closeConnection();
}
else
{
$model = new Model;
$model->select();
$connection->closeConnection();
}
?>