0

我的 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();

我在哪里做错了?

4

1 回答 1

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();
}
于 2012-07-26T19:32:59.247 回答