mysqli
是 PHP 中的一个扩展,用于与 MySQL 数据库进行交互。它提供了面向对象和过程式的 API,使得开发者能够方便地执行 SQL 查询、处理结果集以及管理数据库连接。
mysqli
是对 MySQL 数据库原生协议的封装,因此性能较高。mysqli
主要有两种使用方式:
mysqli
适用于需要与 MySQL 数据库进行交互的各类 PHP 应用,包括但不限于:
以下是一个简单的 mysqli
封装示例,采用面向对象风格:
class MySQLiDB {
private $host;
private $username;
private $password;
private $dbname;
private $conn;
public function __construct($host, $username, $password, $dbname) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
$this->connect();
}
private function connect() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die("连接失败: " . $this->conn->connect_error);
}
}
public function query($sql) {
return $this->conn->query($sql);
}
public function escape($string) {
return $this->conn->real_escape_string($string);
}
public function close() {
$this->conn->close();
}
}
// 使用示例
$db = new MySQLiDB('localhost', 'root', 'password', 'testdb');
$result = $db->query('SELECT * FROM users');
while ($row = $result->fetch_assoc()) {
echo $row['username'] . '<br>';
}
$db->close();
通过以上封装和示例代码,你可以更方便地在 PHP 项目中使用 mysqli
进行数据库操作,并遵循最佳实践来确保安全性和性能。
领取专属 10元无门槛券
手把手带您无忧上云