Answers for "how to store connection object in the constant in php"

PHP
0

how to store connection object in the constant in php

<?php

include_once('IConnectInfo.php');

class Database implements IConnectInfo
{

    private static $instance = null;
    private $conn;

    private $server = IConnectInfo::HOST;
    private $currentDB = IConnectInfo::DBNAME;
    private $user = IConnectInfo::UNAME;
    private $pass = IConnectInfo::PW;

    private function __construct()
    {
        try {
            $this->conn = new PDO("mysql:host=$this->server;dbname=$this->currentDB", $this->user, $this->pass
            );
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->conn->exec('set names utf8');
            echo $this->server . " connected successfully" . PHP_EOL;
        } catch (PDOException $e) {
            echo "Connection failed: " . $e->getMessage();
            die;
        }
    }

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new Database();
        }

        return self::$instance;
    }

    public function getConnection()
    {
        return $this->conn;
    }


    public function getSelectQueryResult($query = '')
    {
        try {
            $query = $this->conn->prepare($query);
            $query->execute();
            return $query->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            echo $query . "<br>" . $e->getMessage();
        }
    }
}
Posted by: Guest on July-08-2020

Code answers related to "how to store connection object in the constant in php"

Browse Popular Code Answers by Language