Include a PHP file in another PHP file
Most of the time, when we work with PHP and MySQL database, we have to write the PHP codes to connect to the MySQL database in many PHP files. It is very annoying to do so if there are too many PHP files which needs the codes. To make it easier, it is a good idea to put the PHP code for connecting to the MySQL database in a separate PHP file and import into other PHP files.
Here is an example:
First is the PHP file containing the segment of the PHP codes for connecting to the MySQL database, I called it “connectmysql.php”:
<?php mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed"); mysql_select_db("DataBase Name")or die("Connection Failed"); ?>
Now here is the file which requires the segment of the PHP codes for connecting to the MySQL database in the beginning of the file, I called this file “needsconnectmysql.php”:
1 2 3 4 5 | <?php //We import the codes from the PHP file "connectmysql.php" require_once ('connectdatabase.php'); //and we type the rest of the code here ?> |
Note that the codes of the “connectmysql.php” are now included in the “needsconnectmysql.php”.
require_once () PHP function only works when you want to include a file only once, if you want to include more than once, use the PHP function require().
Similar Posts:
- WordPress – Auto create Post into the MySQL database from Excel data file
- Import Excel, CSV file data into MySQL database table
- Display UTF8 encoding records such as Chinese or Asian languages from MySQL database with PHP
- Check how many record in the MySQL database matches the query
- Think Aloud Method





Add A Comment