OOP MySQLi Connect


OOP MySQLi Connect

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

类内数据库我有函数db_num

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

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

混合使用mysqli对象样式和过程样式是不好的做法。

试试这个:

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

在调用db_num()之前,请确保连接到数据库,例如:

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

在我看来,更干净的方法是在构造函数内部调用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");
<?php
/** 
 * Creating a class for the database connection
 * To start using the database connection like this: $database = DatabaseFactory::getFactory()->getConnection();
*/
class DatabaseFactory {
    protected $servername = "servername";
    protected $username = "root";
    protected $password = "root";
    protected $dbname = "databasename";
    private static $factory;
    private $database;
    public static function getFactory() {
        if(!self::$factory) {
            self::$factory = new DatabaseFactory();
        }
        return self::$factory;
    }
    public function getConnection() {
        if(!$this->database) {
            try {
                $this->database = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
            } catch (mysqli_sql_exception $e) {
                $error = $e->getMessage();
                echo "Error:" .$error;
                exit;
            }
        }
        return $this->database;
    }
}