1

次のメッセージが表示されます。

Notice: 未定義の変数: 12 行目の /var/www/PDO/Functions/PDOFunctions.php の dbh 致命的なエラー: /var/www/PDO/Functions/PDOFunctions の非オブジェクトでメンバ関数 prepare() を呼び出します。 12行目のphp

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

私のコードの問題は何ですか?

4

3 に答える 3

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 が壊れていて動作しないことに注意してください。そのため、修正も加えました。

于 2012-12-01T01:45:54.800 に答える
2

変数グローバルを一度宣言しないと、すべての関数で使用できます。

アクセスする必要がある各関数でグローバル変数を宣言します。

http://php.net/manual/en/language.variables.scope.phpの使用例を参照してくださいglobal

于 2012-12-01T01:34:02.963 に答える
2

PHP では、関数内のグローバル変数にアクセスするには、global キーワードを使用してグローバル スコープに属していることを宣言する必要があります。

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

関数で使用されるすべての変数は、グローバル スコープからインポートするように宣言されていない限り、その関数に対してローカルです。

NOTICE エラーは、予期しないことを行っている可能性があることを警告するのに役立ちます。

于 2012-12-01T01:34:05.087 に答える