1 回答

TA貢獻1856條經驗 獲得超17個贊
在目前的狀態下,它對你來說根本沒有用處。mysqli 連接始終是相同的三行代碼,沒有必要為其添加類。
要使用 mysqli 連接到數據庫,請使用:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'db_name');
$mysqli->set_charset('utf8mb4'); // always set the charset
然后你可以編寫一個類,它將數據庫連接作為參數__construct()。
class Test {
? ? private \mysqli $db = null;
? ? public function __construct(\mysqli $db) {
? ? ? ? $this->db = $db;
? ? }
? ? function runQuery($sql) {
? ? ? ? $query = $this->db->query($sql);
? ? }
}
就是這樣。盡管您確實應該嘗試創建一個更有用的 mysqli 抽象類,或者更好,但使用 PDO 代替。如果你想編寫 mysqli 包裝類,你可以從以下想法開始(根據你的需要進行調整):
class DBClass extends mysqli {
? ? public function __construct($host = null, $username = null, $passwd = null, $dbname = null, $port = null, $socket = null) {
? ? ? ? // Enable error reporting and call mysqli constructor
? ? ? ? mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
? ? ? ? parent::__construct($host, $username, $passwd, $dbname, $port, $socket);
? ? ? ? $this->set_charset('utf8mb4'); // always set the proper charset which should be utf8mb4 99.99% of the time
? ? }
? ? public function safeQuery(string $sql, array $params = []): ?array {
? ? ? ? // Prepare statement:
? ? ? ? $stmt = $this->prepare($sql);
? ? ? ? // If the statement has parameters then bind them all now
? ? ? ? if ($params) {
? ? ? ? ? ? $stmt->bind_param(str_repeat("s", count($params)), ...$params);
? ? ? ? }
? ? ? ? // Execute it and get results if there are any
? ? ? ? $stmt->execute();
? ? ? ? if ($result = $stmt->get_result()) {
? ? ? ? ? ? return $result->fetch_all(MYSQLI_BOTH);
? ? ? ? }
? ? ? ? // If the query was INSERT or UPDATE then return null
? ? ? ? return null;
? ? }
}
然后,即使使用 mysqli,您也可以用簡單的一行執行任何 SQL 語句。
- 1 回答
- 0 關注
- 108 瀏覽
添加回答
舉報