0

How do I use PDO FetchObject results with the $this variable?

Have a page class which is used to display a page that has its details stored in a database. Each page has a title and a description specific to that page. In production, there are many more variables and functions than those shown here.


class Page  
{  
  var $title;
  var $description;

  function load_page() 
  {
    $this->get_page_meta();

    // do some more stuff and then
    // send $this variable to template view that displays page
  }


  function get_page_meta()
  {
    $stmt = $dbh->query("SELECT title, description FROM pages WHERE page_id = '1'");

    $stmt->fetch(PDO::FETCH_OBJ);
    // HOW DO I MAKE THE RESULT SET REFERENTIAL USING $this?
    // I want $this->title to be accessible 
    // without assigning $this->title = $result->title
  }
}

csi
  • 9,018
  • 8
  • 61
  • 81
  • 1
    there is an object merging post here don't know if applies to you: http://stackoverflow.com/q/455700/642173 or then would `$this->pdoObj->title;` be an acceptable option for you? It implies that you use `$this->pdoObj = $dbh->query($sql);` – Melsi Nov 02 '11 at 19:40
  • I would prefer to avoid any "children". I would like $this->title as opposted to $this->meta->title. – csi Nov 02 '11 at 20:00
  • And how about merging that is refered to the link above? – Melsi Nov 02 '11 at 20:17
  • Unless I am missing something, the merging would take $this->other_attributes and merge it with $this->db_object to form $this->new_obj->combined_attributes. I would prefer $this->all_attibutes. – csi Nov 02 '11 at 20:22

1 Answers1

1

Try using the FETCH_INTO style, eg

$stmt = $dbh->prepare(...);
$stmt->setFetchMode(PDO::FETCH_INTO, $this);
$stmt->execute();
$stmt->fetch();
$stmt->closeCursor();
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Thank you! I wasn't aware of that functionality. That solves a lot of problems in this project and in others. – csi Nov 03 '11 at 18:01