What would be the preferred method for handling errors when using the PDO to connect to a MySQL database? I was using mysqli_error($this->pdo)
, but I heard this was bad practice. Any feedback would be much appreciated.
class Database
{
/*
* Database properties
*/
private $server = 'localhost';
private $username = 'root';
private $password = 'root';
private $database = 'posts';
public $pdo;
public static $instance;
/**
* Static method used to instantiate singleton
* @return [object] Database object
*/
public static function getInstance()
{
if (!isset($instance)) {
Database::$instance = new Database();
}
return Database::$instance;
}
/**
* Connect to DB when class is instantiated
*/
private function __construct()
{
$this->connect();
}
/**
* Connects to the database
*/
private function connect()
{
// Assign dsn string
$dsn = 'mysql:host=' . $this->server . ';dbname=' . $this->database;
// Assign connection to $pdo
$pdo = new PDO($dsn, $this->username, $this->password);
// $pdo inside the function is added to the objects parameter pdo
else {
$this->pdo = $pdo;
}
}
/**
* Queries database for the argument $sql
* @param string $sql
* @return Sql Query $statement
*/
public function query($sql)
{
// Prepare SQL query
$statement = $this->pdo->prepare($sql);
// return mysql query array
else {
return $statement;
}
}
/**
* Queries for post of id $id
* @param [$id] Post ID
* @return [array]
*/
public function getPost($id)
{
// Query
$stmt = $this->query("SELECT * FROM posts WHERE id=(:id)");
// Binds $id parameter to the PDO
$stmt->bindParam(':id', $id);
// Execute query
$stmt->execute();
// Create an empty array for the posts
$posts = array();
while($row = $stmt->fetch()) {
// Data is fetched from the database as an array
$posts[] = $row;
}
// Return post in an array
return $posts;
}
}
else
s without the initialif ()
s. Technically, shouldn't that produce an error? – Alex L Jan 1 at 20:26mysqli_error()
handler. – zia grosvenor Jan 1 at 21:02