简体   繁体   中英

Creating MYSQLI only once

I'm trying to create my db connection this way. In Functions_BD I would like to create connection to BD and define all my functions (Login, Insert, Selects...). My class looks like this:

 class functions_BD {

 private $mysqli;

 function __construct() {
    require_once 'config.php';
    $mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);   

}

In 'config.php' I've my DB configuration. Then I have some public functions inside "Functions_BD" like this one

public function login($user,$passw){        

        $mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);   

        if (mysqli_connect_errno()) {
            return 2;
        }
        $stmt=$mysqli->prepare("SELECT COUNT(*) FROM users WHERE user= ? AND passw= ? ");
        $stmt->bind_param('ss', $user,$passw);
        $stmt->execute();
        $result = $stmt->fetch();

        if($result>0){          
            return 1;
        }else{              
            return 0;
        }           
    }

If I define $mysqli in each function the code works fine, my question is: is there any way of defining $mysqli only once and using it in all my functions? (Like I tried in the constructor) Or I may define it again every time I do a query?

Just set it in an property ... use in the methods later, if you're using the same connection in others class, try learn and use dependency injection, and about the factory pattern.

In you ctor, just put $this->mysqli = new mysqli( ... ) , and then, in others methods, just use it: $this->mysqli->prepare ...

You code will look something like that:

<?php

class functions_BD 
{
  private $mysqli;

  function __construct() 
  {
    require_once 'config.php';
    $this->mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);
  }

  function login($user, $psw)
  {
    $stmt = $this->mysqli->prepare("SELECT COUNT(*) FROM users WHERE user= ? AND passw= ? ");
    $stmt->bind_param('ss', $user,$passw);
    $stmt->execute();
    $result = $stmt->fetch();

    return $result > 0;
  }
}

You can use the following singleton pattern:

class functions_BD {
  private $mysqli;
  private static $instance;

  public static function get_instance() {
    if (!isset(self::$instance)) {
      self::$instance = new self();
    }
    return self::$instance;
  }

  private function __construct() {
    $this->mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);
  }
}

To use the DB, you can use the following:

$db = functions_BD::get_instance();

The same instance will be called in all your codes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM