How to Connect to MySQL database in Slim framework 4

/ By Arjun / Published on February 10, 2021

Defining MySQL database connection in the Slim 4 framework is pretty simple. In this slim framework 4 tutorial, we gonna create a project with Slim-Skeleton.

If you are looking for Slim Framework 3, follow the link How to configure/load database in Slim Framework 3

Install Slim Framework 4

We recommend you install the Slim Framework with the Composer dependency manager.

The easiest way to start working with Slim is to create a project using Slim-Skeleton as a base by running this bash command:

Replace [app-name] with the desired directory name for your new application.

You can then run it with PHP’s built-in webserver:

upon successful slim 4 project setup, you should able to see output in the browser at http://localhost:8080

How to Connect to MySQL database in Slim framework 4
Output in Browser
Folder Structure of the project.

Add Database Settings

Go to the app directory, open the settings.php file, and pass the database setting to the Settings class along with other settings.

Once settings are in place, open app/dependencies.php file and configure database

Slim framework 4 Database Connection Test

Now open the app/routes.php file and define a route for testing the database connection.

The below code assume that your database has a task table if not update SQL queries in the below sample code.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

5 2 votes
Article Rating
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
7 months ago

Great post, very useful

5 months ago

Thanks man for the guide. I was struggling with the db connection.

ameya pukale
ameya pukale
5 months ago

the post was wonderful and very helpfull. i have one doubt how to use db in controller ?

Francesco R. Di Caprio
Francesco R. Di Caprio
1 month ago

Good article, just one thing: the “flags” have been defined but you have not passed them, so PDO is not actually instructed to use them. Also the “driver” key has been defined but not used

Would love your thoughts, please comment.x