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
  }
}

4
  • 1
    there is an object merging post here don't know if applies to you: 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); Commented Nov 2, 2011 at 19:40
  • I would prefer to avoid any "children". I would like $this->title as opposted to $this->meta->title. Commented Nov 2, 2011 at 20:00
  • And how about merging that is refered to the link above? Commented Nov 2, 2011 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. Commented Nov 2, 2011 at 20:22

1 Answer 1

1

Try using the FETCH_INTO style, eg

$stmt = $dbh->prepare(...);
$stmt->setFetchMode(PDO::FETCH_INTO, $this);
$stmt->execute();
$stmt->fetch();
$stmt->closeCursor();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I wasn't aware of that functionality. That solves a lot of problems in this project and in others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.