How to Connect to MySQL database in Slim framework 4

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 1 vote
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Tom
Tom
1 month ago

Great post, very useful

DMCA.com Protection Status
1
0
Would love your thoughts, please comment.x
()
x