PDO查询失败

时间:2012-07-26 19:26:10

标签: mysql oop pdo

我的PDO课程有问题。我刚刚开始学习OOP而且我真的不知道我犯了什么错误

我的班级代码:

<?php

class admin
{
  private $host = 'mysql:host=localhost;dbname=db501865';
  private $username = 'root';
  private $password = 'root';
  private $conn;


  public function connect() {
      try {
          $conn = new PDO($this->host, $this->username, $this->password);
      } catch ( PDOException $e ) {
          die( 'Connection failed: ' . $e->getMessage() );
      }
      return $conn;
  }

  public function disconnect( $conn ) {
      $conn = '';
  }


  public function listReal()
    {
        $this ->connect();
        $real = $conn->query('SELECT * FROM `real`');
        echo '<ul>';
        foreach ($real as $row)
        {
            echo'<li><img src="'.$row['image'].'"></li>';
        }
        $real -> closeCursor();
        echo'</ul>';
    }

}
?>

执行以下代码后,我的浏览器出现500错误。

$db = new admin;
$db -> listReal();

我犯了错误?

1 个答案:

答案 0 :(得分:1)

您必须使用$this->var_name作为成员变量 如果您已连接,也无需连接。

class admin
{
    private $host = 'mysql:host=127.0.0.1;dbname=test';
    private $username = 'root';
    private $password = 'local@pass';
    private $conn;


    public function connect() {
        if($this->conn) return;
        $this->conn = new PDO($this->host, $this->username, $this->password);
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function disconnect( $conn ) {
        $conn = '';
    }


    public function listReal()
    {
        $this ->connect();
        $real = $this->conn->query('SELECT * FROM `real`');

        echo '<ul>';
        foreach ($real as $row)
        {
            echo'<li><img src="'.$row['user_id'].'"></li>';
        }
        $real -> closeCursor();
        echo'</ul>';
    }

}
try{
    $db = new admin;
    $db -> listReal();
} catch(Exception $e) {
    echo 'error: '.$e->getMessage();
}
相关问题