php mysqli类,包含常用的mysqli函数
封面图
•
2025-09-20
•
PHP
158
0
0
0
在 PHP 中,`mysqli` 是一个面向对象的接口,用于与 MySQL 数据库进行交互。它提供了比旧的 `mysql_*` 函数更安全、更强大的功能,特别是支持预处理语句(Prepared Statements)以防止 SQL 注入。 下面是一个包含常用 `mysqli` 函数的类示例,你可以将其用作数据库连接和操作的基础类: --- ### ✅ 示例:PHP mysqli 类(含常用函数) ```php <?php class Database { private $host = "localhost"; private $username = "root"; private $password = ""; private $database = "test_db"; private $conn; // 构造函数,连接数据库 public function __construct() { $this->conn = new mysqli($this->host, $this->username, $this->password, $this->database); if ($this->conn->connect_error) { die("Connection failed: " . $this->conn->connect_error); } } // 获取数据库连接 public function getConnection() { return $this->conn; } // 执行查询(适用于 SELECT) public function query($sql) { $result = $this->conn->query($sql); return $result; } // 预处理查询(适用于 INSERT, UPDATE, DELETE) public function prepare($sql) { $stmt = $this->conn->prepare($sql); return $stmt; } // 绑定参数(用于预处理语句) public function bindParam($stmt, $types, ...$params) { $stmt->bind_param($types, ...$params); } // 执行预处理语句 public function execute($stmt) { return $stmt->execute(); } // 获取结果集(适用于 SELECT 查询) public function getResults($result) { $rows = []; while ($row = $result->fetch_assoc()) { $rows[] = $row; } return $rows; } // 获取最后插入的 ID public function getLastInsertId() { return $this->conn->insert_id; } // 获取受影响的行数 public function getAffectedRows() { return $this->conn->affected_rows; } // 获取错误信息 public function getError() { return $this->conn->error; } // 关闭连接 public function close() { $this->conn->close(); } // 析构函数,关闭连接 public function __destruct() { $this->close(); } } ``` --- ### 🔧 使用示例: ```php <?php include 'Database.php'; $db = new Database(); // 1. 查询数据 $sql = "SELECT * FROM users"; $result = $db->query($sql); $users = $db->getResults($result); print_r($users); // 2. 插入数据(使用预处理) $stmt = $db->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $db->bindParam($stmt, "ss", "John Doe", "john@example.com"); $db->execute($stmt); echo "Last Insert ID: " . $db->getLastInsertId(); // 3. 更新数据 $stmt = $db->prepare("UPDATE users SET name = ? WHERE id = ?"); $db->bindParam($stmt, "si", "Jane Smith", 1); $db->execute($stmt); echo "Affected Rows: " . $db->getAffectedRows(); // 4. 删除数据 $stmt = $db->prepare("DELETE FROM users WHERE id = ?"); $db->bindParam($stmt, "i", 1); $db->execute($stmt); // 5. 错误检查 if ($db->getError()) { echo "Error: " . $db->getError(); } ``` --- ### 📌 常见 `mysqli` 函数说明: | 函数 | 说明 | |------|------| | `new mysqli()` | 创建一个新的数据库连接 | | `query()` | 执行 SQL 查询(适用于 SELECT) | | `prepare()` | 准备 SQL 语句(用于预处理) | | `bind_param()` | 绑定参数到预处理语句 | | `execute()` | 执行预处理语句 | | `fetch_assoc()` | 获取结果集中的一行作为关联数组 | | `insert_id` | 获取最后插入的 ID | | `affected_rows` | 获取最近一次操作影响的行数 | | `error` | 获取最近一次错误信息 | | `close()` | 关闭数据库连接 | --- 如果你需要一个更高级的封装(如 ORM 或查询构建器),可以考虑使用 Laravel 的 Eloquent 或者 Doctrine。但对于大多数项目,上述 `mysqli` 类已经足够使用。 是否需要我为你扩展这个类,比如添加事务支持、分页、或模型类?
上一篇:
php ubb函数
下一篇:
php 打造完美柱状图
标题录入,一次不能超过6条
返回顶部
留言
留言
评论