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;
}
}
}
答案 0 :(得分:1)
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.