S
S
Svyatoslav Nemato2016-10-21 15:20:09
PHP
Svyatoslav Nemato, 2016-10-21 15:20:09

How to prevent connection to the database more than 1 time?

class DB {
  public static $mysqli;
  private $connect = true;

  function __construct() {
    if ($this->connect) {
      $mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
      $mysqli->set_charset("utf8");
      $this->mysqli = $mysqli;
      $this->connect = false;
    }
    }

Each time the DB class descendants are called, a new connection to the database occurs, how to prevent this?
[ Solution ]
My jamb, due to inattention, called the class several times, which is why this error occurred.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Zelensky, 2016-10-21
@SergeyZelensky-Rostov

<?php
class DB {
  
  public static $mysqli;
  
  private $connect = true;
  
  private $_instance = null;
  
  
  private function __construct() {
    
    if ($this->connect) {
      
      $mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
      
      $mysqli->set_charset("utf8");
      
      $this->mysqli = $mysqli;
      
      $this->connect = false;
      
    }
    
  }
    private function __clone(){}
  
  public static function init(){
    
    if($_instance === null){
      
      self::$_instance = new self();
      
    }
    
    return self::$instance;
    
  }
  
}

this thing is called singletone

J
jaxel, 2016-10-21
@jaxel

2016 is in the yard. No need to use mysqli. Use some kind of ORM thread or at least PDO.
Singleton is rather an anti-pattern, and definitely not the best solution for a database. What will you do if you need to connect to two bases?

I
illuzor, 2016-12-06
@iLLuzor

Filter/Liquify

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question