如何在Flight PHP框架中使用MySQLi?替换PDO遇连接错误求解决
Got it, let's figure out why you're hitting that error and fix it right away!
Why the Error Happens
The core issue here is that PDO and mysqli have totally different constructor parameter formats. PDO uses a single DSN string (like mysql:host=localhost;dbname=test) as its first argument, but mysqli expects separate, individual values for each connection detail. When you swapped PDO for mysqli and kept the DSN string, mysqli tried to treat that entire string as a hostname—naturally, it couldn't resolve that weird "address," hence the "getaddrinfo failed" error.
Correct Way to Register MySQLi in Flight PHP
You need to pass parameters in the exact order mysqli's constructor expects: host, username, password, database name (plus optional port or socket if your setup requires it).
Here's the fixed registration code:
// Register mysqli service with proper, separated parameters Flight::register('db', 'mysqli', array('localhost', 'user', 'pass', 'test')); // Grab the mysqli instance $db = Flight::db();
Example Query with MySQLi
Keep in mind mysqli's query workflow is a bit different from PDO. Here's how to run your select query properly:
$result = $db->query("SELECT * FROM `test_table` LIMIT 0, 30"); // Fetch a single row as an associative array $x = $result->fetch_assoc(); // Or fetch all rows at once if needed // $allRows = $result->fetch_all(MYSQLI_ASSOC);
Quick Tips to Avoid Headaches
- Check mysqli Extension: Make sure the mysqli extension is enabled in your PHP setup. You can confirm this by running
phpinfo()and looking for the mysqli section. - Enable Exception Handling: Unlike PDO, mysqli doesn't throw exceptions by default. To make debugging easier, turn on exception-based error handling right after getting the instance:
$db->setAttribute(MYSQLI_ATTR_ERRMODE, MYSQLI_ERRMODE_EXCEPTION); - Optional Connection Params: If your MySQL server uses a non-standard port or socket, add those to the parameter array:
// Example for port 3307 Flight::register('db', 'mysqli', array('localhost', 'user', 'pass', 'test', 3307));
内容的提问来源于stack exchange,提问作者user1762634

