0

Hello Community,
I'm trying to connect to my database using PDO but for some reason it keep coming back saying "Undefined variable: db_c" db_c is the variable I've chossen for the name of my database connection. I've placed the database connection in another file, and I'm trying to connect to the database in another file that contains functions.

So I've included the database file at the top of the page. Then that is what give me the error. So I tried putting the include at the top of the function I'm trying to use and I got it to work, but I don't want to include the database file at the top of every function.

2
Contributors
1
Reply
12
Views
3 Years
Discussion Span
Last Post by cereal
0

The problem is the scope of the function not the include(), a function will not consider an external variable unless this is global and you define it inside the function, for example:

<?php

include 'conn.php';

function q()
{
    global $conn;
    $stmt = $conn->query("select * from users limit 1");
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

print_r(q());

As alternative you can pass the connection as argument of the function:

<?php

include 'conn.php';

function q($conn)
{
    $stmt = $conn->query("select * from users limit 1");
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

print_r(q($conn));

Another alternative is to return from the included file, for example:

$conn = new PDO('config', '', '');
return $conn;

And then:

<?php

$conn = include 'conn.php';

function q($conn)
{
    $stmt = $conn->query("select * from users limit 1");
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

print_r(q($conn));

Check the documentation:

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.