我是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
中使用时,它无法连接到数据库答案 0 :(得分:8)
混合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");
答案 1 :(得分:0)
<?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;
}
}