Search code examples
phpmysqlerror-handlingincluderequire

How to properly use PHP require


I have 3 files: index.php, db.php (database), and functions.php

here is an example what is in each file:

database.php:

define ("DB_HOST", "localhost");
define ("DB_USER", "root");
define ("DB_PASS", "1234");
define ("DB_NAME", "test");

try {
    $dsn = "mysql:dbname=".DB_NAME.";host=".DB_HOST;
    $dbh = new PDO($dsn, DB_USER, DB_PASS);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

index.php:

require $_SERVER['DOCUMENT_ROOT']."/config/db.php";
require $_SERVER['DOCUMENT_ROOT']."/config/functions.php";

if(isLoggedIn()) {
    echo "hi";
}

functions.php:

function isLoggedIn() {
    require $_SERVER['DOCUMENT_ROOT']."/config/db.php";

    $stmt = $dbh->prepare("SELECT * FROM users....");
    $stmt->execute();
}

The error i get is:

Notice: Constant DB_HOST already defined in /var/www/config/database.php

what i tried:

I tried to replace require with require_once in all my files but the error that it gives is here:

Fatal error: Uncaught Error: Call to a member function prepare() on null in functions.php


Solution

  • So, since it didn't make a sense to you my last answer here is a full answer of what you can do to get rid of this problem once for all:

    db.php

    <?php
    $host="localhost"; 
    $user="root"; 
    $password="1234"; 
    $db="test"; 
    
        try {
            $dbh = new PDO("mysql:host=$host;dbname=$db",$user,$password);
        } catch (PDOException $e) {
            die("DB ERROR: ". $e->getMessage());
        }
    ?>
    

    index.php

    require_once $_SERVER['DOCUMENT_ROOT']."/config/db.php";
    
    if(isLoggedIn($dbh)) {
        echo "hi";
    }
    

    functions.php

    function isLoggedIn($dbh) {
    $stmt = $dbh->prepare("SELECT * FROM users....");
    $stmt->execute(); 
    }
    function anotherfunction($dbh) {
    $stmt = $dbh->prepare("SELECT * FROM others....");
    $stmt->execute(); 
    }
    

    The above corrections will save you the pain of looking after the requires, you require the db.php once so that now you have access to its variable and pass as argument whenever needed.

    Note: Thanks Phil for fruitful comments and good elaboration.