Include a PHP file in another PHP file
Most of the time, when we have to work between PHP and MySQL database, we have to write the PHP codes for connecting to the MySQL database in many PHP files very often. It is very annoying to do so if there are too many PHP files which needs these 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 when any PHP file needs that segment of codes, it could use PHP function require_once () or require() to import the PHP file with codes.
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”:
<?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().






