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.

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:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.