I want to use PDO for mysql connectivity in php. I need to have the PDO connection object which must be available on multiple files. The database connection must be also a class. Many answers found here are not satisfying. Please explain the correct method to achieve it.
The current method which I follow is: Filename:connectClass.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
class connect
{
public $db;
public $isConnected;
public function __construct()
{
$this->isConnected = true;
try {
$this->db=new PDO('mysql:host=localhost;dbname=dbname','root','rootpass');
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e) {
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
}
$obj=new connect();
?>
The connection object is accessed in Filename:addContentClass.php
<?php
include_once 'class/connectClass.php';
class addContent extends connect
{
public function insertContent($title, $content, $page_title, $meta_tags) {
try {
$qry = $this->db->prepare("INSERT INTO tblPageContents (PageName, PageTitle, PageMeta, PageKeyWords, PageContents, PageFooter, PageShortName) VALUES (?, ?, ?, ?, ?, ?, ?)");
$data = array($title, $content, $page_title, $meta_tags);
$qry->execute($data);
echo "<div id=\"dialog-ci\" title=\"Content updation success\" style=\"color:green\">Content insertion success</div>";
}
catch(PDOException $e)
{
echo 'Query failed'.$e->getMessage();
}
}
}
?>
The problem with this code is that I need to use extends every time.