1

私は PDO の学習を始めましたが、まだ少し PHP の初心者です。知識を増やすためのプロジェクトを行っていますが、最初のハードルで立ち往生しています。

このエラーが発生しました: このコードの 37 行目の非オブジェクトでメンバー関数 prepare() を呼び出します。これはdatabase.class.phpからのものです

<?php
// Include database class
include 'config.php';

class Database{
private $host      = DB_HOST;
private $user      = DB_USER;
private $pass      = DB_PASS;
private $dbname    = DB_NAME;

private $dbh;
private $error;

public function __construct(){
    // Set DSN
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
    // Set options
    $options = array(
        PDO::ATTR_PERSISTENT    => true,
        PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
    );
    // Create a new PDO instanace
    try{
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
    // Catch any errors
    catch(PDOException $e){
        $this->error = $e->getMessage();
    }
}

// this variable holds the temporary statement
private $stmt;

// prepare our values to avoid SQL injection
public function query($query){
    $this->stmt = $this->dbh->prepare($query);
}

// use switch to select the appropiate type for the value been passed
// $param = placeholder name e.g username, $value = myusername
public function bind($param, $value, $type = null){
    if (is_null($type)) {
        switch (true) {
            case is_int($value):
                $type = PDO::PARAM_INT;
                break;
            case is_bool($value):
                $type = PDO::PARAM_BOOL;
                break;
            case is_null($value):
                $type = PDO::PARAM_NULL;
                break;
            default:
                $type = PDO::PARAM_STR;
        }
    }
// run the binding process
$this->stmt->bindValue($param, $value, $type);
}

// execute the prepared statement
public function execute(){
    return $this->stmt->execute();
}

// returns an array of the results, first we execute and then fetch the results
public function resultset(){
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

// same as resultset() except this returns a single result
public function result_single(){
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

// count the number of rows from the previous delete, update or insert statement
public function rowCount(){
    return $this->stmt->rowCount();
}

// last insert id return the last id of the insert made, useful if you need to run a further
// query on the row you just inserted and need the id as the reference
public function lastInsertId(){
    return $this->dbh->lastInsertId();
}

// transactions allow you to rollback if a set of queries fail but it also allows ensures
// we avoid errors due to users interaction while half of the queries are still being written

// the following code begins a transaction
public function beginTransaction(){
    return $this->dbh->beginTransaction();
}

// end a transaction
public function endTransaction(){
    return $this->dbh->commit();
}

// rollback a transaction
public function cancelTransaction(){
    return $this->dbh->rollBack();
}

// this dumps the PDO information from the prepared statement for debug purposes
public function debugDumpParams(){
    return $this->stmt->debugDumpParams();
}

}

?>

index.php でこのコードを実行している最初のページ

<?php

// Include database connection class
include 'includes/database.class.php';
include 'includes/bug.class.php';

$database = new Database;
$bugs = new Bugs;
$bugs->find_all_rows();

echo "<pre>";
print_r($rows);
echo "</pre>";

echo "Number of rows: " . $bugs->rowCount() . "<br />";


?>

これは、bugs.class.php ファイルである find_all_rows 関数を実行するページです。

<?php
class Bugs {

    public function find_all_rows() {
      return self::find_by_sql('SELECT * FROM tbl_priority');   
    }

    public function find_by_sql($sql="") {
      global $database;
      $database->query($sql);
      $rows = $database->resultset();

      return $rows;
    }
}
?>

これらのタイプのエラーをよりよく追跡するのに役立つデバッグ ツールはありますか?それとも、明らかな間違いを見つけるのに PDO に精通していないだけですか?

4

2 に答える 2

2

@papajaは頭に釘を打ちました。PDO 接続に失敗したため、準備メソッドを実行するための PDO オブジェクトがありません。

頭のてっぺんから、$dsn 文字列の終了引用符が欠落していると思います。$this->dbname の後、セミコロンの前に以下を追加するとよいでしょう:

. "'"

これは、二重引用符で囲まれた単一引用符です。次の構文を使用して DSN 文字列を作成します。

"mysql:host=$this->HOST;dbname=$this->DATABASE"

とにかく、問題が何であるかを正確に知るために、テストファイルを作成してください。テスト ファイルは次のようになります。

class TestDatabase{

    private $host      = DB_HOST;
    private $user      = DB_USER;
    private $pass      = DB_PASS;
    private $dbname    = DB_NAME;
    private $dbh;


    public function __construct(){

        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;

        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );

        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
}

try catch ブロック内で PDO オブジェクトのインスタンス化を実行していないことに注意してください。実稼働環境ではこれを行うことはありませんが、接続のすべての詳細を含む致命的な例外がスローされるため、テストには役立ちます。

ここで、テスト クラスをインスタンス化し、受け取ったエラーをデバッグして続行します。繰り返しますが、キャッチされない PDO 例外であるため、以前のエラーよりも詳細になります。

于 2013-08-04T19:02:57.790 に答える
0

同じエラーが発生し、上記のコードでは修正できませんでした。

あなたのコードでは、これが PDO Sending Error の理由である問題であるため、簡単に修正できます。

public function __construct(){
    // Set DSN
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
    // Set options
    $options = array(
        PDO::ATTR_PERSISTENT    => true,
        PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
    );
    // Create a new PDO instanace
    try{
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
    // Catch any errors
    catch(PDOException $e){
        $this->error = $e->getMessage();
    }
}

私はPHP 5.5を使用していますが、誰かが同じエラーを抱えている場合、彼はこれを必要とします

$dns の後に、 $this->dbname の場所にこれを追加する必要があります。";";

これだけが PHP 5.5 で機能し、 $this->dbname では機能しません。"'";

public function __construct(){
    // Set DSN
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . ";";
    // Set options
    $options = array(
        PDO::ATTR_PERSISTENT    => true,
        PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
    );
    // Create a new PDO instanace
    try{
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
    // Catch any errors
    catch(PDOException $e){
        $this->error = $e->getMessage();
    }
}
于 2014-07-11T09:50:18.353 に答える