This is what I have as my database class:
<?php
// Define configuration
define("DB_RDBMS", "mysql");
define("DB_HOST", "localhost");
define("DB_NAME", "ccaweb");
define("DB_USER", "ccawebroot");
define("DB_PASS", "Ni2o7AwE");
class database {
// Database Managment System (Database Type)
private $rdbms = DB_RDBMS;
// Database Host Address/IP
private $dbhost = DB_HOST;
// Database Name
private $dbname = DB_NAME;
// Database User Name
private $dbuser = DB_USER;
// Database Password
private $dbpass = DB_PASS;
//
private $con = false;
public function __construct ()
{
//connect to database
if (!$this->con)
{
//not yet connected, make a connection
try
{
$this->db = new PDO($this->rdbms.':host='.$this->dbhost.';dbname='.$this->dbname, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->con = true;
return $this->con;
}
catch (PDOException $e)
{
require_once('/error/database_error.php');
$date = date("d/m : H:i : ");
file_put_contents('logs/db.connection.error.txt', $date.$e->getMessage().PHP_EOL,FILE_APPEND);
exit();
}
}
else
{
//already connected - do nothing and show true
return true;
}
}
}
?>
This is what I'm doing to use the class:
// Import database class file
include_once '../library/class/database.class.php';
//create new database instance
$db = new database();
// Create Table
$query = "DROP TABLE IF EXISTS `courseannouncement`;
CREATE TABLE IF NOT EXISTS `courseannouncement` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`courseId` varchar(10) NOT NULL,
`title` varchar(100) NOT NULL,
`announcementText` text NOT NULL,
`createdBy` int(11) NOT NULL,
`createdDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`deleted` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)";
$sth = $db->prepare("$query");
$sth->execute();
?>
However Im getting the error that: Fatal error: Call to undefined method database::prepare() in D:..\installDatabase.php on line 22
So I tried changing the database class to
class database extends PDO {
but that still gives me an error
Can anyone point me in the direction of what I'm doing wrong? Is using a class best practice for PDO database connection?
Also, Should I be using singleton? I've seen various places where they've said it's good to, but also alot of posts where it's said it's bad to use singletons.