PHP Database Connection and Functions

This is just a question on when database connections are opened based on file includes within PHP.  

So I have a config.php:

$host = 'localhost';
$dbUserName = 'dev';
$dbName = 'dev';
$dbPassword = 'devpw';

$db = new mysqli($host, $dbUserName, $dbPassword, $dbName);

Open in new window

I also have functions.php:
function myAvatar($userID)
    include 'config.php';
    $sql    = "select avatar from users where id = " . $userID;
    $result = $db->query($sql);
    $row    = $result->fetch_assoc();

    return $row['avatar'];

Open in new window

So my question is that if I include that functions page on a page but don't call a function from it, on page load does it still open a database connection because I'm including the config.php file?


include 'functions.php';

echo 'some text';

Open in new window

LVL 12
Nathan RileyFounderAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dan CraciunIT ConsultantCommented:

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Willem van PeltCommented:
No, if the database connection is made inside a function, the connection is not made until you actually call that function.
You can try this easily by specifying an incorrect password: your script will then bork as soon as it tries to connect to the database.
Dan CraciunIT ConsultantCommented:
@Willem: my bad, I did not read until the end.

This is what creates the database connection:
$db = new mysqli($host, $dbUserName, $dbPassword, $dbName);

Since you include functions.php, (not config.php, as I thought), that line is not actually executed until you call myAvatar.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.