gpt4 book ai didi

php - OOP MySQLi 连接

转载 作者:行者123 更新时间:2023-12-01 14:03:42 24 4
gpt4 key购买 nike

我是 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 - OOP MySQLi 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29321795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com