2012-12-19 67 views
2

我試圖從我的表中使用PDO檢索數據,只有我似乎無法輸出任何內容到我的瀏覽器,我只是得到一個普通的白色頁面。使用PDO從MySQL獲取結果

try { 
    // Connect and create the PDO object 
    $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); 
    $conn->exec("SET CHARACTER SET utf8");  // Sets encoding UTF-8 

     $lastIndex = 2; 

     $sql = "SELECT * FROM directory WHERE id > :lastIndex AND user_active != '' LIMIT 20" 
     $sth = $conn->prepare($sql); 
     $sth->execute(array(':lastIndex' => $lastIndex)); 

     $c = 1; 
     while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { 
      echo 'ALL STYLING ETC RESULTS HERE'; 
     $c++; 
     } 

    $conn = null;  // Disconnect 
} 
+1

你有沒有設置'$ userdb'和'$ passdb'變量?你有沒有在phpmyadmin或mysql shell中試過查詢是否返回任何結果? – Kush

+0

如果您刪除了'try {}',那麼您可能會遇到一些錯誤,以至於什麼不起作用 – Damp

+1

啓用異常'$ conn-> setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION);'如果您嘗試{ }' - 這正是例外情況 - 不被壓制! – mpen

回答

4

示例。 這是您的DBC類

<?php 

class dbc { 

    public $dbserver = 'server'; 
    public $dbusername = 'user'; 
    public $dbpassword = 'pass'; 
    public $dbname = 'db'; 

    function openDb() {  
     try { 
      $db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . ''); 
     } catch (PDOException $e) { 
      die("error, please try again"); 
     }   
     return $db; 
    } 

    function getAllData($qty) { 
     //prepared query to prevent SQL injections 
     $query = "select * from TABLE where qty = ?"; 
     $stmt = $this->openDb()->prepare($query); 
     $stmt->bindValue(1, $qty, PDO::PARAM_INT); 
     $stmt->execute(); 
     $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); 
     return $rows; 
    }  
?> 

你的PHP頁面:

<?php 
require "dbc.php"; 

$getList = $db->getAllData(25); 

foreach ($getList as $key=> $row) { 
     echo $row['columnName'] .' key: '. $key; 
    }