OOP MySQLi Connect

Uar*_*ged 2 php oop

我是OOP的新手.我有班级数据库

class Database{
private $host;
private $user;
private $pass;
private $db;
public $mysqli;

function db_connect(){
    $this->host = 'localhost';
    $this->user = 'root';
    $this->pass = '';
    $this->db = 'db';

    $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
    return $this->mysqli;
}
Run Code Online (Sandbox Code Playgroud)

内部类数据库我有函数db_num

function db_num($sql){
    $num = mysqli_num_rows(mysqli_query($this->mysqli,"{$sql}"));
    return $num;
}
Run Code Online (Sandbox Code Playgroud)

但是当我在con参数$ this-> mysqli中使用时,它无法连接到数据库

Mar*_*o A 8

混合mysqli对象样式和程序样式是不好的做法.

试试这个:

function db_num($sql){
    $result = $this->mysqli->query($sql);
    return $result->num_rows;
}
Run Code Online (Sandbox Code Playgroud)

在打电话之前一定要连接到数据库db_num(),例如:

$db = new Database();
$db->db_connect();
$db->db_num("SELECT fields FROM YourTable");
Run Code Online (Sandbox Code Playgroud)

在我看来,更简洁的方法是db_connect在构造函数内部调用:

class Database{
  private $host;
  private $user;
  private $pass;
  private $db;
  public $mysqli;

  public function __construct() {
    $this->db_connect();
  }

  private function db_connect(){
    $this->host = 'localhost';
    $this->user = 'root';
    $this->pass = '';
    $this->db = 'db';

    $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
    return $this->mysqli;
  }

  public function db_num($sql){
        $result = $this->mysqli->query($sql);
        return $result->num_rows;
  }
}

$db = new Database();
$db->db_num("SELECT fields FROM YourTable");
Run Code Online (Sandbox Code Playgroud)