0

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?

Robert
  • 10,126
  • 19
  • 78
  • 130

2 Answers2

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.

Dai
  • 141,631
  • 28
  • 261
  • 374
  • Only thing that came to mind was storing the connection in a session variable so that it would be available across multiple pages withoug having to include the same code across many pages. As the saying goes, "write once use everywhere" – Robert Sep 01 '15 at 22:14
  • @RobertRocha Do not store database connections in session state: http://stackoverflow.com/questions/6078843/storing-database-connection-in-a-session-variable – Dai Sep 01 '15 at 22:19
0

Place your common code in a separate file. Then use

include('myfile.php');

where you want the common code to appear

tllewellyn
  • 903
  • 2
  • 7
  • 28