OOP MySQLi Connect

2019-04-16 09:06发布

Im newbie in OOP. I have class Database

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;
}

Inside class Database i have function db_num

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

But it cant connect to database when im using in con argument $this->mysqli

标签: php oop
1条回答
三岁会撩人
2楼-- · 2019-04-16 09:45

It is bad practice to mix mysqli object style and procedural style.

Try this:

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

Be sure to connect to the database before you call db_num(), e.g.:

$db = new Database();
$db->db_connect();
$db->db_num("SELECT fields FROM YourTable");

A cleaner way in my opinion would be to call db_connect inside the constructor:

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");
查看更多
登录 后发表回答