CodeIgniter中MAMP环境下数据库主机配置报错及配置方法咨询
First, let's clear up the core confusion here: you're mixing up two entirely separate ports—your web server's port (81) and your MySQL database's port (3307). The localhost:81 is the address you use to access your website in a browser, not the address MySQL listens on. That's exactly why you're getting the "Unknown MySQL server host" error: MySQL doesn't recognize "localhost:81" as a valid database host.
Correct Configuration for database.php
You need to specify the MySQL host and port separately. MAMP runs MySQL on port 3307, so we'll define that explicitly, while keeping the hostname as a standard local database address. Here's the working setup:
$db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', // Use '127.0.0.1' if you hit socket-related issues 'username' => 'root', // Default MAMP MySQL username 'password' => 'root', // Default MAMP MySQL password 'database' => 'your_actual_db_name', // Replace with your database name 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE, 'port' => 3307, // Critical: MAMP's MySQL port goes here );
Why This Works
- The
hostname(localhostor127.0.0.1) points directly to your local MySQL server, no web port needed here. - The
portparameter tells CodeIgniter to connect to MySQL on 3307 instead of the default 3306. - Your web server's 81 port only matters when accessing your site in the browser (e.g.,
http://localhost:81/your_ci_project)—it has zero impact on how the app connects to the database.
Quick Troubleshooting Note
If localhost still causes issues, switch to 127.0.0.1 as the hostname. Sometimes localhost tries to use a Unix socket instead of TCP/IP, which might not align with MAMP's MySQL configuration.
内容的提问来源于stack exchange,提问作者Yuva Ammu

