Move the PHP MySQL Connection Code To Its Own File

This is a free resource from my online course, From Idea To Launch, where I teach you how to build a full Laravel web application, step by step, at beginner's speed. Learn more →

In a full web application, you’ll be working with a lot of separate — but well-organized — files.

It’s best to use different files to establish a separation of concerns: each file contains code that performs a distinct piece of functionality.

So it’s good to start practicing this now.


Move the MySQL connection code to a separate file

For example, in your full web application, your database connection code will live in a separate file.

But right now, your MySQL code is contained in your controller file. To complete this exercise, you’re going to separate it out into its own file.

There are just two simple steps:

  1. Move all of the MySQL code it to its own file, and name the file accordingly (e.g. db-connection.php)
  2. include that file from within your [object]-controller.php

And remember: after you make the changes, your page should look exactly the same, because you didn’t change any content, you just changed the code’s organization.

You will continue to see (and have already seen) this mantra of optimizing your code’s organization pop up over and over again. Organization is key, when building a web app. Great organization is crucial to ensure that:

  1. Your code is designed as efficiently as possible.
  2. It’s easy to build upon and expand your application, moving forward.