0

我知道这已经被问过好几次了,但我没有找到与我的情况相匹配的那个,所以不得不问。

我有两个文件
1) connection.php

class Database {

    protected $dbh;

    public function __construct() {
        $dsn = 'mysql:dbname=dbname;host=localhost';
        $user = 'dbuser';
        $pass = 'dbpass';

        try {
            $this->dbh = new PDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
    }

    public function displayInfo() {
        $stmt = $this->dbh->prepare("SELECT fname, lname FROM info");
        return $stmt->execute();
    }

}

$db = new Database();

2.) info.php

require_once 'connection.php';

$result = $db->displayInfo();

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    echo $row['fname']. " " . $row['lname'];
}

我知道我不能使用fetch()with $result,如果它在同一页面中,我可以使用$stmt->fetch()但不知道如何PDO fetch从另一个页面调用它。

4

2 回答 2

1

PDOStatement::execute()方法在成功时返回 true,在失败时返回 false——不是查询的结果。您需要返回您的声明:

public function displayInfo() {
    $stmt = $this->dbh->prepare("SELECT fname, lname FROM info");
    $stmt->execute();
    return $stmt;
}

这样,$result变量实际上就是你的语句,你可以调用fetch()它的方法。

更好的方法是从displayInfo()方法内部进行获取并仅返回结果,而不必依赖于将您的数据库好东西带到类之外,例如:

class Database 
{

   protected $dbh;

   public function __construct() {
      $dsn = 'mysql:dbname=dbname;host=localhost';
      $user = 'dbuser';
      $pass = 'dbpass';

      try {
         $this->dbh = new PDO($dsn, $user, $password);
      } catch (PDOException $e) {
         echo 'Connection failed: ' . $e->getMessage();
      }
   }

   public function getDisplayInfo() {
      $stmt = $this->dbh->prepare("SELECT fname, lname FROM info");
      if( $stmt->execute() ) {
         return $stmt->fetch(PDO::FETCH_ASSOC);
      }
      // Query failed
      return false;
   }
}

$db = new Database();

$results = $db->getDisplayInfo();

foreach($results as $row) {
   echo $row['fname']. " " . $row['lname'];
}
于 2013-04-09T19:47:21.930 回答
-1

正确的代码。在PDO 标签 wiki中查看详细信息

class Database {

    protected $dbh;

    public function __construct() {
        $dsn = 'mysql:dbname=dbname;host=localhost';
        $user = 'dbuser';
        $pass = 'dbpass';
        $opt = array(
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );
        $this->dbh = new PDO($dsn, $user, $password, $opt);
    }

    public function displayInfo() {
        $stmt = $this->dbh->prepare("SELECT fname, lname FROM info");
        $stmt->execute();
        return $stmt->fetchAll();
    }

}
于 2013-04-09T20:00:39.033 回答