MySQL Connection File Shortcut in PHP

How to set up a database connection for use in multiple PHP files

Man working on notebook
Dominik Pabis/E+/Getty Images

Many website owners use PHP to enhance the capabilities of their web pages. When they combine PHP with the open source relational database MySQL, the list of capabilities grows immensely. They can establish login credentials, conduct user surveys, set and access cookies and sessions, rotate banner ads on their site, host their own user forums and open their own online stores, among many other features that are not possible without a database.

MySQL and PHP are compatible products and are widely used together by website owners. The MySQL code can be included directly in the PHP script. Both are located on your web server, and most web servers support them because they are so widely used. The server-side location provides reliable security for the data your website uses.

Connecting Multiple Web Pages to One MySQL Database

If you have a small website, you probably don't mind typing your MySQL database connection code into the PHP script for a few pages. However, if your website is large and many of the pages require access to your MySQL database, you can save time with a shortcut. Put the MySQL connection code in a separate file and then call the saved file where you need it.

For example, use the SQL code below in a PHP script to log in to your MySQL database. Save this code in a file called datalogin.php.

 <?php // Connects to my Database mysql_connect("", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); ?> 

Now, whenever you need to connect one of your web pages to the database, you include this line in PHP file for that page:

 //MySQL Database Connect include 'datalogin.php'; 

When your pages connect to the database, they can read from it or write information to it. Now that you can call MySQL easily, use it to set up an address book or a hit counter for your website.


mla apa chicago
Your Citation
Bradley, Angela. "MySQL Connection File Shortcut in PHP." ThoughtCo, Nov. 27, 2016, Bradley, Angela. (2016, November 27). MySQL Connection File Shortcut in PHP. Retrieved from Bradley, Angela. "MySQL Connection File Shortcut in PHP." ThoughtCo. (accessed January 24, 2018).