Including the same file over many pages

时间:2015-09-01 22:09:27

标签: php mysql

I am writing a simple app for a school project that is not too big. I have the following files: signup.php

login.php

view_photos.php

that have the following in common: they connect to a database and execute queries. In every file I find myself repeating the your typical database connection code snippet:

$mysql = new mysqli( 'localhost', 'root', '', 'imagebox');

    if( $mysql->connect_errno ) {

        echo "Connection failure: " . $mysqli->connect_error;
        exit();
    }

Is there a way to do this once in the index.php file and pass the connection to other pages without having to repeat the same line in every page that requires a database connection?

2 个答案:

答案 0 :(得分:2)

Use PHP's include feature, though I recommend using require instead (as require aborts script execution if the file doesn't exist).

Documentation is here: http://php.net/manual/en/function.require.php

Use require_once to prevent duplicate inclusion if you have cycles in your include-dependency tree.

答案 1 :(得分:0)

Place your common code in a separate file. Then use

include('myfile.php');

where you want the common code to appear