how to store connection object in the constant in php

Solutions on MaxInterview for how to store connection object in the constant in php by the best coders in the world

showing results for - "how to store connection object in the constant in php"
Lukas
19 Feb 2018
1<?php
2
3include_once('IConnectInfo.php');
4
5class Database implements IConnectInfo
6{
7
8    private static $instance = null;
9    private $conn;
10
11    private $server = IConnectInfo::HOST;
12    private $currentDB = IConnectInfo::DBNAME;
13    private $user = IConnectInfo::UNAME;
14    private $pass = IConnectInfo::PW;
15
16    private function __construct()
17    {
18        try {
19            $this->conn = new PDO("mysql:host=$this->server;dbname=$this->currentDB", $this->user, $this->pass
20            );
21            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
22            $this->conn->exec('set names utf8');
23            echo $this->server . " connected successfully" . PHP_EOL;
24        } catch (PDOException $e) {
25            echo "Connection failed: " . $e->getMessage();
26            die;
27        }
28    }
29
30    public static function getInstance()
31    {
32        if (!self::$instance) {
33            self::$instance = new Database();
34        }
35
36        return self::$instance;
37    }
38
39    public function getConnection()
40    {
41        return $this->conn;
42    }
43
44
45    public function getSelectQueryResult($query = '')
46    {
47        try {
48            $query = $this->conn->prepare($query);
49            $query->execute();
50            return $query->fetchAll(PDO::FETCH_ASSOC);
51        } catch (PDOException $e) {
52            echo $query . "<br>" . $e->getMessage();
53        }
54    }
55}
56