PHP:mysqli构造函数是否支持传入数组?
Great question! I’ve made the switch from PEAR::MDB2 to MySQLi myself a while back, so I totally get the urge to keep using that familiar DSN array pattern instead of juggling individual connection parameters. Let’s break this down:
Short Answer
MySQLi does not natively support passing a DSN array directly to its connection methods (either the mysqli class constructor or the procedural mysqli_connect() function). It requires explicit, individual parameters for host, username, password, database name, etc. But don’t worry—you can easily replicate the MDB2-style DSN array workflow with a simple wrapper function.
How to Replicate DSN Array Support
Here’s a quick, reusable function that takes a MDB2-like DSN array and converts it into the parameters MySQLi needs:
function mysqli_connect_from_dsn(array $dsn) { // Extract parameters with sensible defaults (match MDB2's DSN keys) $host = $dsn['hostspec'] ?? 'localhost'; $username = $dsn['username'] ?? ''; $password = $dsn['password'] ?? ''; $database = $dsn['database'] ?? ''; $port = $dsn['port'] ?? 3306; $socket = $dsn['socket'] ?? null; // Create the MySQLi connection $conn = new mysqli($host, $username, $password, $database, $port, $socket); // Handle connection errors (adjust this to your error handling style) if ($conn->connect_error) { trigger_error("MySQL connection failed: " . $conn->connect_error, E_USER_ERROR); } return $conn; }
Usage Example
You can use this exactly like you did with MDB2:
// Your familiar DSN array $dsn = [ 'hostspec' => 'localhost', 'database' => 'your_project_db', 'username' => 'db_user', 'password' => 'secure_password', 'port' => 3307 // Optional, if you're using a non-default port ]; // Get your MySQLi connection $mysqli = mysqli_connect_from_dsn($dsn);
Why This Works
This wrapper maps the keys from your MDB2 DSN array (like hostspec, username) to the corresponding parameters MySQLi expects. It also includes sensible defaults (like localhost for host, 3306 for port) so you don’t have to fill in every key unless you need to override them.
Bonus: Procedural Style Option
If you prefer procedural MySQLi over the object-oriented approach, you can adjust the wrapper to use mysqli_connect() instead:
function mysqli_connect_from_dsn(array $dsn) { $host = $dsn['hostspec'] ?? 'localhost'; $username = $dsn['username'] ?? ''; $password = $dsn['password'] ?? ''; $database = $dsn['database'] ?? ''; $port = $dsn['port'] ?? 3306; $socket = $dsn['socket'] ?? null; $conn = mysqli_connect($host, $username, $password, $database, $port, $socket); if (!$conn) { trigger_error("MySQL connection failed: " . mysqli_connect_error(), E_USER_ERROR); } return $conn; }
内容的提问来源于stack exchange,提问作者Lamar

