PHP: OOP connection to database use multiple -
i use code connect database
class db { private $connect; public function connect(){ if(!$this->connect){ include "config.php"; echo "connect"; $this->connect = mysqli_connect($config['host'],$config['user'],$config['pass']); if($this->connect){ $select = mysqli_select_db($this->connect,$config['name']); if(!$select){ echo "not found database !"; exit(); } } else { echo "not connect database !"; exit(); } } return $this->connect; } public function query($query) { $result = $this->connect()->query($query); return $result; } }
and use code connect , after select database
$db = new db(); $connect = $db->connect(); $db = new db(); $way = $db->select("select * `setting`");
after run code , print on page :
connectconnect
why not work if(!$this->connect){
in line 3
, connect twice ?
make use of singleton pattern provide this
class db { private $connect; protected static $instance; public static function getinstance() { if (null === self::$instance) { self::$instance = new self; } return self::$instance; } protected function __clone() {} protected function __construct() {} public function connect(){ if(!$this->connect){ include "config.php"; echo "connect"; $this->connect = mysqli_connect($config['host'],$config['user'],$config['pass']); if($this->connect){ $select = mysqli_select_db($this->connect,$config['name']); if(!$select){ echo "not found database !"; exit(); } } else { echo "not connect database !"; exit(); } } return $this->connect; } public function query($query) { $result = $this->connect()->query($query); return $result; } }
then use class instance anywhere in app
$db = db::getinstance(); $connect = $db->connect(); $db = db::getinstance(); $way = $db->select("select * `setting`");
Comments
Post a Comment