2015-04-04 17 views
2

我對PHP並不陌生,但我對所有這些PDO和MVC的東西都很陌生。我基本上試圖從數據庫回顯數據到頁面。PDO MVC從數據庫迴應數據到頁面

模型(_dashboard.php)

<?php 

require_once('_connection.php'); 

class ConnectToDB { 
    private $db; 

    public function __construct(){ 
     $this->db =new connection(); 
     $this->db = $this->db->dbConnection(); //uses the connection in connection class 
    } 

    public function teachersStudents($id){ 
     // this function checks whether the user name exists and if its a match 
     if(!empty($id)){ 
      $st = $this->db->prepare("SELECT * FROM students WHERE id=?"); 
      $st->bindParam(1, $id); 
      $st->execute(); 

      if ($st->rowCount() == 1) { 
       $result = $st->fetchAll(); 
       foreach($result as $row){ 
        echo "<tr>"; 
        echo "<td>" . $row['id'] . "</td>"; 
        echo "</tr>"; 
       } 
      } 
     } 
    } 

} 

// Close database connection 
$dbh = null; 

?> 

視圖(dashboard.phtml)

<?php 

    require_once('_dashboard.php'); 

    $object = new ConnectToDB(); 
    $object->teachersStudents($id); 

    echo $result; 
?> 

結果

說明:未定義變量:導致

我可能這樣做是完全錯誤的,所以推動正確的方向將不勝感激。這是控制器,但與它無關。

控制器

<?php 

    $view = new stdClass(); 
    $view->pageTitle = 'Dashboard'; 
    require_once('views/dashboard.phtml'); 
+0

如何從模型傳遞'$ result'查看? – jsxqf 2015-04-05 02:14:38

+0

有一個require_once我忘了從代碼複製,代碼更新 – CarlRyds 2015-04-05 14:39:03

回答

1

$result是不確定的改變你的函數返回的結果。

$result = $st->fetchAll(); 
return $result; 

然後將你的代碼視圖,而不是顯示HTML:

require_once('_dashboard.php'); 

$object = new ConnectToDB(); 
$result = $object->teachersStudents($id); 

foreach($result as $row){ 
echo "<tr>"; 
echo "<td>" . $row['id'] . "</td>"; 
echo "</tr>"; 
} 
+0

在頁面上獲取此警告:爲foreach()'提供的無效參數' – CarlRyds 2015-04-05 20:19:55

+0

@CarlR是否修改了上面的函數? var_dump($ result);'查看數組的內容 – meda 2015-04-05 20:20:49

+0

'var_dump($ result);'給出NULL' – CarlRyds 2015-04-05 20:47:13