MySQL Connection File Shortcut in PHP

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

My SQL coding
iStock / Getty Images Plus 

Many website owners use PHP to enhance the capabilities of their webpages. 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 user forums, and open online stores, among many other features that are not possible without a database.

MySQL and PHP are compatible products and are frequently 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. The server-side location provides reliable security for the data your website uses.

Connecting Multiple Webpages 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("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
?> 

Now, whenever you need to connect one of your webpages to the database, you include this line in PHP in the 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, use it to set up an address book or a hit counter for your website.

 

Format
mla apa chicago
Your Citation
Bradley, Angela. "MySQL Connection File Shortcut in PHP." ThoughtCo, Feb. 12, 2018, thoughtco.com/mysql-connect-files-in-php-2694111. Bradley, Angela. (2018, February 12). MySQL Connection File Shortcut in PHP. Retrieved from https://www.thoughtco.com/mysql-connect-files-in-php-2694111 Bradley, Angela. "MySQL Connection File Shortcut in PHP." ThoughtCo. https://www.thoughtco.com/mysql-connect-files-in-php-2694111 (accessed May 20, 2018).