1
votes

I'm getting the following message:

Notice: Undefined variable: dbh in /var/www/PDO/Functions/PDOFunctions.php on line 12 Fatal error: Call to a member function prepare() on a non-object in /var/www/PDO/Functions/PDOFunctions.php on line 12

$dbh = new PDO('mysql:host=localhost;dbname=pdo', 'root', 'xxxxxxxxxxx');
global  $dbh;


function PDOFetch($Var)
{
    $sth = $dbh->prepare("$Var"); //Error Line
    $sth->execute();
    $result = $sth->fetchAll();
    return $result; 
}

function PDONumb ($Var)
{
    $Query = $dbh->prepare("{$Var}");
    $Execute->execute();
    $count = $Execute->rowCount();
    return $count;
}

What is the problem with my code?

3
global $dbh goes inside the functions. - Tim Cooper
Take a look at my simple DByte library. - Xeoncross
The problem is you don't know how global works. You should have googled this and read the documentation before asking a question on Stack Overflow... - meagar

3 Answers

3
votes

Using global variables is bad practice. For something as easy as this, you could rewrite your code as a simple class. In doing so, you also get the added benefit of easily being able to create and use multiple database handles.

class Db 
{
    private $dbh = null;

    public function __construct()
    {
        $this->dbh = new PDO('mysql:host=localhost;dbname=pdo', 'root', 'xxxxxxxxxxx');
    }

    public function PDOFetch($Var)
    {
        $sth = $this->dbh->prepare("$Var"); //Error Line
        $sth->execute();
        $result = $sth->fetchAll();
        return $result; 
    }

    public function PDONumb ($Var)
    {
        $sth = $this->dbh->prepare("{$Var}");
        $sth->execute();
        $count = $sth->rowCount();
        return $count;
    }
    // Other methods here
}

Then it's:

$dbc1 = new Db();
$dbc2 = new Db();  // Hey I have 2 connections now, cool
$result1 = $dbc1->PDOFetch(..);
$result2 = $dbc2->PDOFetch(..);

Note, that your PDONumb was broken and wouldn't work, so I threw in a fix for that as well.

2
votes

In PHP, to access a global variable in a function, you have to declare that it belongs to global scope by using the global keyword.

function PDOFetch($Var)
{
    global $dbh;
    $sth = $dbh->prepare("$Var"); //Error Line
    $sth->execute();
    $result = $sth->fetchAll();
    return $result; 
}

All variables used in a function are local to that function unless declared to be imported from the global scope.

The NOTICE error is a helpful warning that you may be doing something you didn't expect.

2
votes

You don't declare a variable global once and then it's available in all functions.

You declare the global variable in each function that needs to have access to it.

See the examples of using global in http://php.net/manual/en/language.variables.scope.php