2013-08-23 67 views
0

我正在修補一個'應該'允許我輕鬆執行fetchall查詢並在foreach語句中顯示結果的類。我假設所有工作正常,因爲我沒有錯誤。至於foreach - 這一定是問題嗎?我如何通過$connect->query()獲得結果?我是新來的,在我的函數中使用任何數據庫OOP框架,所以我可能完全錯誤的行。PDO查詢類

<? 

error_reporting(1); 

class dbconnect { 

private $host; 
private $database; 
private $username; 
private $password; 

private $pdo; 
private $error; 

    public function __construct() { 

     $this->host  = "localhost";    // Host 
     $this->database = "images";     // Database Name 
     $this->username = "*";    // Username 
     $this->password = "*"; // Password 
     $options = array(
      PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' 
     ); 

     try { 
      $this->pdo = new PDO("mysql:host={$this->host};dbname={$this->dbname};charset=utf8", $this->username, $this->password, $options); 
     } 
     catch(PDOException $e) { 
      $this->error = $e->getMessage(); 
     } 

    } 

    public function query($query) { 

     try { 
      $stmt = $this->pdo->prepare($query); 
      $stmt->execute(); 
     } catch(PDOException $ex) { 
      die("Failed to run query: " . $ex->getMessage()); 
     } 

     $rows = $stmt->fetchAll(); 
     return $rows; 

    } 

} 

$connect = new dbconnect; 
$rows = $connect->query("select * from photos"); 
foreach($rows as $row): 
    print $row['id']; 
endforeach; 



?> 

回答

2

您在query內部聲明的$rows變量不能被外部訪問,它是該函數的本地變量。最有可能的,你只是想return這些結果給調用者:

$rows = $stmt->fetchAll(); 
return $rows; // return value from function... 

,並有來電捕捉在其自己的變量返回值:

$rows = $connect->query("select * from images"); // ... is received by caller 
foreach($rows as $row): 

還檢查了dougjore的答案,你在query方法內混合$this->stmt$stmt

+0

謝謝你的幫助,完成了必要的調整後完美工作。錯誤報告設置不正確,pdo實例也引用了另一個dbname變量。 – JoshMc

2

很確定你是不是曾經實際執行查詢:

 $this->stmt = $this->pdo->prepare($query); 
     $stmt->execute(); 

我相信(我可能是錯的,我是相當新的PDO自己,我還沒有建立一個類爲此),你需要說$ this-> stmt-> execute();

+0

以下是Mattias Buelens所說的。我還沒有讀到:) – wiscWeb

+0

正確,但我認爲你可能不想讓最後一條語句在你的'dbconnect'對象中存在。只需'$ stmt'而不是'$ this-> stmt'應該做的。 –

+0

是的,我自己也很新。但我知道有一個作爲'$ this-> stmt'和一個'$ stmt'不會做到這一點。 – wiscWeb

1

你可以做

// PDO :: FETCH_ASSOC:返回按列名索引作爲你的結果返回數組設置

$this->stmt = $this->pdo->prepare($query); 
$this->stmt->execute(); 

while ($result = $this->stmt->fetch(PDO::FETCH_ASSOC)) 
{ 

    //do something with the result 
} 

看看這裏爲更多的選擇來獲取PDO查詢結果: http://php.net/manual/en/pdostatement.fetch.php

0
$connect = new dbconnect; 
$sql="select * from photos"; 
$stmt=$connect->pdo->prepare($sql); 
$stmt->execute(); 
$result=$stmt->fetch(PDO::FETCH_ASSOC); 
foreach($result as $key => $value) { 
    echo $key . "-" . $value . "<br/>"; 
}