Including database connection file in php

Including database connection file in php

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Scope Trap: Why include Doesn't Always Merge Variables

It is a common assumption in PHP that simply including a file will magically merge its variables into your current namespace. While this often feels like it works, relying on it for application state management leads to fragile code and confusing errors. You recently encountered a classic scope issue where $db was defined in dbconnection.php, included in login.php, yet PHP threw a "Undefined variable: db" error.

The root cause lies in how the include statement functions versus how global variables are accessed. When you use include('dbconnection.php'), PHP executes the code inside that file within its own local scope. The $db object is created locally to that specific execution context. Unless you explicitly declare it as a global variable or pass it by reference, it remains invisible to the code running in login.php.

To fix this immediately without refactoring your entire architecture, you must use the global keyword inside the login.php file before accessing $db. However, relying on the global keyword is widely considered an anti-pattern in modern PHP development. It couples your functions to a specific variable name and location, making the code harder to test and less secure against race conditions if multiple requests hit the script simultaneously.

The Correct Approach: Dependency Injection via Global State

The standard practice for managing database connections across multiple files is to treat the connection object as shared application state. You can achieve this by initializing the variable in your configuration file (like session-config.php) or a dedicated bootstrap file, rather than inside a logic-heavy file like dbconnection.php.

Here is how you should restructure your setup to ensure $db is accessible everywhere without using global inside every function:

1. centralize the connection in a bootstrap file:

Create a file named config/database.php:

<?php
// config/database.php
$host = getenv('DB_HOST') ?: 'localhost';
$dbname = getenv('DB_NAME') ?: 'your_database';
$username = getenv('DB_USER') ?: 'root';
$password = getenv('DB_PASS') ?: '';

try {
    $db = new mysqli($host, $username, $password, $dbname);
    
    if ($db->connect_errno > 0) {
        // Log the error or throw an exception; do not die() here to allow graceful failure handling
        error_log("Database connection failed: " . $db->connect_error);
        exit('Unable to connect to database');
    }
    
    // Set charset explicitly
    $db->set_charset("utf8mb4");
} catch (Exception $e) {
    die('Fatal Error: ' . $e->getMessage());
}

2. Initialize the global variable in your entry point:

In login.php (or your main index.php), load the configuration first and explicitly assign the connection to a global variable:

<?php
// login.php

// Load all dependencies
require_once 'config/session-config.php';
require_once 'config/database.php'; // The connection is now in global scope
require_once 'functions/functions.php';
require_once 'vendor/autoload.php'; // For password_hash_lib

// Ensure the connection is available globally if not already done in db.php
if (!isset($db)) {
    include 'config/database.php';
}

if (isset($_POST['data'])) {
    $data = $_POST['data'];
    $auth = json_decode($data);
    
    // Pass data or rely on global state depending on your function signature
    authenticate($auth->Email, $auth->Password);
}

By ensuring $db exists in the global scope of login.php before any other logic runs, your authenticate() function will find it. If your authenticate() function is defined inside login.php, it will automatically have access to global variables. If you move authenticate() into a separate file later, you should pass $db as an argument or use the global keyword in that specific function, but keep the initialization centralized.

Security and Architecture Trade-offs

Your current implementation has another significant security vulnerability unrelated to the scope error: SQL Injection. In your query, you are interpolating user input directly into the string: SELECT * FROM app_users WHERE user_email='$Email'.

If a user inputs ' OR '1'='1 as their email, the resulting SQL query becomes:
SELECT * FROM app_users WHERE user_email='' OR '1'='1'

This condition is always true, effectively bypassing authentication and returning all users. You must use prepared statements to prevent this.

Since you are using mysqli, here is how you should modify your connection file to support prepared statements:

<?php
// config/database.php
$db = new mysqli($host, $username, $password, $dbname);
if ($db->connect_errno > 0) {
    die('Unable to connect to database [' . $db->connect_error . ']');
}
$db->set_charset("utf8mb4");

And update your authenticate function in login.php:

function authenticate($email, $password) {
    global $db; // Explicitly access the global connection
    
    // Use prepared statements
    $sql = "SELECT * FROM app_users WHERE user_email = ?";
    
    if ($stmt = $db->prepare($sql)) {
        $stmt->bind_param("s", $email); // 's' indicates string parameter
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            if (password_verify($password, $row['user_password_hash'])) {
                $_SESSION["user_auth_details"] = 
                    $row['user_id'] . "+" . $row['user_email'] . '+' . 
                    $row['user_name'] . "+" . $row['user_display_image'] . "+" . 
                    $row['user_display_name'];
                
                header("Location: " . $_SESSION['page_url']);
                exit; // Always exit after a header redirect
            }
        }
        
        $stmt->close();
    } else {
        die('Query preparation failed: ' . $db->error);
    }
}

Moving Towards Frameworks

While organizing files into session-config.php, dbconnection.php, and functions.php is a valid exercise in learning PHP, it often leads to "spaghetti code" where variable scope becomes the primary challenge. As your application grows, this manual state management becomes unsustainable.

If you find yourself constantly wrestling with global variables, include paths, and database connection scopes, it might be time to consider adopting a framework like Laravel. Laravel handles dependency injection, configuration management, and database connections out of the box, eliminating the need for manual global declarations and reducing security risks by enforcing best practices like prepared statements automatically. For more information on modern PHP architectures, you might find resources at https://laravelcompany.com useful, though mastering raw PHP structure first is an excellent foundation.

Our network