2012-12-01 26 views
0

我收到以下消息:

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; 
} 

什么是我的代码的问题?

+2

'global $ dbh'进入函数内部。 –

+0

看看我的简单[DByte库](https://github.com/Xeoncross/DByte)。 – Xeoncross

+0

问题是你不知道'global'是如何工作的。你应该用google搜索并阅读文档,然后再问Stack Overflow的问题...... – meagar

回答

2

在PHP中,在函数中访问一个全局变量,你必须声明,它属于全球范围内使用全球关键字。

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

除非声明为从全局范围导入,否则函数中使用的所有变量都是该函数的局部变量。

NOTICE错误是一个有用的警告,您可能正在做一些您没有料到的事情。

+0

修复了这个问题,定时器让我在10分钟内将问题标记为答案:) thankyou –

3

使用全局变量是不好的做法。对于像这样简单的事情,您可以将您的代码重写为简单的类。在此过程中,您还可以轻松创建和使用多个数据库句柄。

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 
} 

然后,它的:

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

请注意,您PDONumb被打破,是行不通的,所以我用一个固定的扔这一点。

+0

将查看这个入侵到我的系统!谢谢!是的,我只是刚刚审查一个:) –