PHP连接MySQL数据库的多种方法及专业级错误处理指南
文章目录
作为网站开发者,高效安全地连接数据库是核心技能。本文将深入探讨PHP连接MySQL的三种主流方法,并分享专业级的错误处理技巧。
一、环境准备与安全注意事项
前置条件:
- PHP 7.4+(PHP 8.x推荐)
- MySQL 5.6+ 或 MariaDB 10.2+
- 启用PDO和MySQLi扩展(php.ini中取消注释)
安全规范:
- 永远不要使用root账户连接
- 敏感信息(如密码)存储在环境变量中
- 最小化数据库用户权限
# .env 文件示例
DB_HOST=localhost
DB_NAME=production_db
DB_USER=app_user
DB_PASS=Jk!9s2*Fq#zP
二、三种主流连接方法详解
方法1:MySQLi(面向对象方式)- 高性能MySQL专用
<?php
declare(strict_types=1);class MySQLiConnector {private mysqli $connection;public function __construct() {$this->connect();}private function connect(): void {try {$this->connection = new mysqli($_ENV['DB_HOST'],$_ENV['DB_USER'],$_ENV['DB_PASS'],$_ENV['DB_NAME'],3306 // 显式指定端口);if ($this->connection->connect_errno) {throw new RuntimeException("MySQLi Connection Error ({$this->connection->connect_errno}): " . $this->connection->connect_error);}// 设置字符集防止注入$this->connection->set_charset('utf8mb4');} catch (Throwable $e) {error_log("[DB] Connection failed: " . $e->getMessage());throw $e;}}public function query(string $sql, array $params = []): mysqli_result {$stmt = $this->connection->prepare($sql);if (!$stmt) {throw new RuntimeException("Prepare failed: ({$this->connection->errno}) {$this->connection->error}");}if ($params) {$types = str_repeat('s', count($params));$stmt->bind_param($types, ...$params);}if (!$stmt->execute()) {throw new RuntimeException("Execute failed: ({