Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- PHP PDO-MYSQL : How to use database connection across different classes
- class connection{
- private $host = 'localhost';
- private $dbname = 'devac';
- private $username = 'root';
- private $password ='';
- public $con = '';
- function __construct(){
- $this->connect();
- }
- function connect(){
- try{
- $this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
- $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
- }catch(PDOException $e){
- echo 'We're sorry but there was an error while trying to connect to the database';
- file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
- }
- }
- }
- class account_info{
- function getAccountInfo(){
- $acc_info = $this->con->prepare("SELECT * FROM account_info");
- $acc_info->execute();
- $results = $acc_info->fetchAll(PDO::FETCH_OBJ);
- foreach ($results as $key) {
- $results->owner_firstname;
- }
- }
- }
- include_once 'classes/connection.class.php';
- include_once 'classes/accountinfo.class.php';
- $con = new connection();
- $info = new account_info();
- $info->getAccountInfo();
- $con = new connection();
- $info = new account_info();
- $info = new account_info();
- class account_info {
- private $con;
- public function __construct(connection $con) {
- $this->con = $con->con;
- }
- public function getAccountInfo(){
- $acc_info = $this->con->prepare("SELECT * FROM account_info");
- $acc_info->execute();
- $results = $acc_info->fetchAll(PDO::FETCH_OBJ);
- foreach ($results as $key) {
- $results->owner_firstname;
- }
- }
- }
- include_once 'classes/connection.class.php';
- include_once 'classes/accountinfo.class.php';
- $con = new connection();
- $info = new account_info($con);
- $info->getAccountInfo();
- class connection {
- private static $hInstance;
- public static function getInstance() {
- if (!(self::$hInstance instanceof self)) {
- self::$hInstance = new self();
- }
- return self::$hInstance;
- }
- /* your code */
- }
- $database = connection::getInstance();
- $database->con->prepare(....)
Add Comment
Please, Sign In to add comment