Function file will not recognize included PDO database connection

1.1k views Asked by At

I have a func.php file that contains a function that gets my user's details:

require_once 'connection.php';

function getUI($username){

    $query = "SELECT * FROM usernames WHERE username = ?";

    $sth = $pdo->prepare($query);

    $sth->bindValue(1, $username);

    $sth->execute();

    $result = $sth->fetch(PDO::FETCH_ASSOC);

    return $result;
} 

in my connection.php I have:

require_once 'details.php';

$pdo = new PDO("mysql:host=" . $dabhost . "; dbname=" . $dabname ."", $dabusern, $dabpassw);

and in details.php I have:

$dabhost = "localhost";
$dabname = "dab1";
$dabusern = "root";
$dabpassw = "root";

And ultimately, I have my userdetails.php that has a bunch of HTML code and displays the results that the function getUI() would bring back. I require func.php at the beginning:

require_once 'folder1/func.php';

My directory looks like this:

rootfolder/userdetails.php
rootfolder/folder1/details.php
rootfolder/folder1/connection.php
rootfolder/folder1/func.php

The issue is that when I open userdetails.php, I get an error in my php_error.log file that says the following:

PHP Notice:  Undefined variable: pdo in /rootfolder/folder1/func.php on line 58
PHP Fatal error:  Call to a member function prepare() on null in /rootfolder/folder1/func.php on line 58

Where if I were to just put all the code at the top of my userdetails.php, it would work and bring back the expected results. Therefore, there is something wrong with how I am requiring the files/scope of the variables I think...

Could someone explain to me what am I doing wrong?

Your help is much appreciated!

Thanks a lot!

UPDATE:

Passing my $pdo connection as a second argument in the function solved my proble, but now I am unable to retrieve x result from my returned $return variable, for instance:

echo $result['date'];

It says that the variable $result is not defined. Any idea why is this occurring?

Thanks a lot again!

2

There are 2 answers

2
castis On

When you declare

function getUI($username) {}

$pdo is not available because it is outside the scope of the function.

You'll need to pass it in as an additional parameter or find some other mechanism for getting $pdo inside getUI().

If you need more information

3
AudioBubble On
require_once 'connection.php';

function getUI($username,$pdo){

    $result = null ;

    $query = "SELECT * FROM usernames WHERE username = ?";

    $sth = $pdo->prepare($query);

    $sth->bindValue(1, $username);

    $sth->execute();

    $result = $sth->fetch(PDO::FETCH_ASSOC);

    return $result;
}

Note : Pass PDO object as second parameter when you call above function.