RbxDealsOwner RbxDealsOwner - 4 months ago 10
PHP Question

Include not working in classes?

I'm not sure if this is just me, but whenever i try to use the

include
method it fails.

<?php
include_once 'db.php';
class Cookies{
public function Verify($Cookie){
echo($dbh);
$CookieStmt = $dbh->prepare("SELECT * FROM Cookies WHERE Cookie=:cookie");
$CookieStmt->bindParam(":cookie",$Cookie);
$CookieStmtExe = $CookieStmt->execute();
if($CookieRow=$CookieStmtExe->fetch(PDO::FETCH_ASSOC)){
if($CookieRow['EndDate']>time()){
return true;
}else{
return false;
}
} else{
return false;
}

}
}
?>


I've also tried
include
inside the function
Verify
but it would always echo out: Notice: Undefined variable: dbh on line 5

And yes I have defined
$dbh
in
db.php


UPDATE: I even tried a direct connection and it's still failing

$dbh = new PDO('mysql:host=127.0.0.1;dbname=baheeg', 'root', '');
class Cookies{
public function Verify($Cookie){
echo($dbh);
$CookieStmt = $dbh->prepare("SELECT * FROM Cookies WHERE Cookie=:cookie");
$CookieStmt->bindParam(":cookie",$Cookie);
$CookieStmtExe = $CookieStmt->execute();
if($CookieRow=$CookieStmtExe->fetch(PDO::FETCH_ASSOC)){
if($CookieRow['EndDate']>time()){
return true;
}else{
return false;
}
} else{
return false;
}

}
}

Answer

The problem is variable scope. Since you assign the variable $dbh outside the function, it's not available inside the function unless you use a global declaration.

<?php
include_once 'db.php';
class Cookies{
    public function Verify($Cookie){
        global $dbh;

        echo($dbh);
        $CookieStmt = $dbh->prepare("SELECT * FROM Cookies WHERE Cookie=:cookie");
        $CookieStmt->bindParam(":cookie",$Cookie);
        $CookieStmtExe = $CookieStmt->execute();
        if($CookieRow=$CookieStmtExe->fetch(PDO::FETCH_ASSOC)){
            if($CookieRow['EndDate']>time()){
                return true;
            }else{
                return false;
            }
        } else{
            return false;
        }
    }
}
?>

You could also put the include statement inside the function, but then you must use include, not include_once because it will only be included in the first function that you call, and the others will skip it.

Comments