如何使用PHP中的OOPS和PDO概念从数据库中获取数据

时间:2015-01-13 11:45:26

标签: php

如何使用PHP中的OOPS和PDO概念从数据库中获取数据:
       我想从数据库中检索数据并在views-one .php页面中显示         使用OOPS和PDO概念。

**controller-one ** 
<?php
public function display_reports()           // declaring function
 {
try { 
  $sql = "SELECT * FROM date WHERE 1";      //query selection

  $query = $this->db->prepare($sql); 
  $query->execute();   
  $data=$query->fetch(PDO::FETCH_ASSOC); //fetching the data from the table

while($row = $query->fetch()){  //i am getting error here

  $id = $row->event_id;         //fetching one coloumn
  $start = $row->start_date;     //fetching one coloumn
  }
}catch (Exception $e) {

} ?>

在上面创建了这个函数,并在此处调用以显示在网页中,

  **views-one **
 $rows = $this->reportsmodel->display_reports();      //calling function here
                id
                <?php echo $rows->$id;?>              //trying to display the content here
                Start
                <?php echo $rows->$start; ?>           //trying to display the content here

这里我得到了这两个人的错误,          注意:未定义的变量:id,          注意:尝试获取非对象的属性          注意:未定义的变量:start          注意:尝试获取非对象的属性         我想循环显示数据。我是PHP的OOP新手,我想练习更多。我尝试使用while和for loop.i我没有得到data.can有人帮我这个吗?谢谢。

1 个答案:

答案 0 :(得分:0)

这是一个解决方案:

public function display_reports(){
    $query = $this->db->prepare("SELECT * FROM date WHERE 1"); 
    $query->execute();  

    return $query->fetchAll(PDO::FETCH_OBJ); // return an array of objects
}


// In the view
$rows = $this->reportsmodel->display_reports();

foreach($rows as $row){ //for each object in the array
    echo $row->id;
}