Include a PHP file in another PHP file

Posted by Shek on May 20, 2008 under PHP | Be the First to Comment | Total View: 3,908 views

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().

Not what you want? Try a Search

Add A Comment

*