【问题标题】:OOP MySQLi ConnectOOP MySQLi 连接
【发布时间】:2015-03-28 19:48:55
【问题描述】:

我是 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 中使用时它无法连接到数据库

【问题讨论】:

标签: php oop


【解决方案1】:

混合使用 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");

【讨论】:

    【解决方案2】:
    <?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;
        }
    }
    

    【讨论】:

    • 用于关闭数据库 = $database -> close(); echo("");
    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多