Codeigniter 4 and MAMP: a few things I have learned while setting up a new project
Comments: Comments Off on Codeigniter 4 and MAMP: a few things I have learned while setting up a new project
I’m starting a new project on the latest Codenigiter 4 framework. My local environment is MacOS Monterey, and I like to build using MAMP Pro 6, CodeKit 3, and Visual Studio. I do rely heavily on the stack/ci community to troubleshoot most issues, but every now and then, one must solve a few issues on their own! If I learn any helpful tips, I plan to post them here.
June 29, 2022
While attempting to install and run Spark migrations from CLI, I have been running into this error a lot:
Unable to connect to the database.
Main connection [MySQLi]: No such file or directory
I’m attempting to install the Shield Auth library, which requires CI4 Settings, and I have had issues getting Spark to run migrations.
The issue is tricky to diagnose as MAMP tends to control its own MySQL and other tools. I have the correct DB settings added to my .env configuration. When I access the MAMP-hosted website through a browser, there are no issues connecting to the database at “localhost”, but the CLI version of CI4 can’t find it.
After lots of searching, I learned that CI4 CLI uses the system-installed version of PHP (I currently have 8.1 and MySQLi is supported). When Spark attempts to connect to “localhost”, it seems that it is not the same “localhost” where MAMP is hosting its database. Remember, MAMP controls its own PHP, MySQL, and other resources. The solution is to get the command line to look for MAMP’s database.
I found this in the following thread: Changing DB hostname to ‘127.0.0.1’ from localhost in your .env file usually solves the problem of running any migrations from the command line.
With the change to ‘127.0.0.1’ and using MAMP, this actually caused the hosted website to lose connection to the DB, as well as the CLI. The solution was a button within MAMP to “Allow network access to MySQL” and I selected the “only from this Mac” option.
After this change, specifying my DB hostname as ‘127.0.0.1’ allowed both the hosted website and CLI to connect to the database. Spark migrations started working as expected.