Search code examples
phpscoperequire-once

Use Require_once() to include database connection variables correctly


I'm a php newbie (but long time developer in other languages) and I'm trying some example db connections in "PHP, MySQL, & JavaScript". It shows an example file to include db connection variables (servername, username, password, database, etc.). I have a php file which has a handful of functions I wrote and one of them has a few SQL queries. For whatever reason, calling require_once in that file doesn't output any errors (I have E_ALL config'd) yet those variables in my database php file are null.

I called an echo with all the variables within that function to see what the heck is going on and of course it prints a blank line. What in the world is out of scope? I have to be missing something simple.

Here's an example of what I'm doing

db_login.php

<?php
    $db_server = 'localhost';
    // ....
?>

functions.php

<?php
    require_once('db_login.php');

    function myfunction() {
        echo "$db_server";
        // ...
    }
?>

Call me crazy, but shouldn't this be simple enough to work?


Solution

  • The variables you declare in db_login.php are globals. In order to access them in your function, you need to use the $GLOBALS variable, e.g. $GLOBALS['db_server'], or declare them as global inside your function using the global keyword, e.g. global $db_server.