SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    May 2008
    Posts
    165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP Data Objects

    I'm just beginning to learn about PHP Data Objects, and all seems to be going well so far.

    However - I'm getting a bit confused over the syntax in the following example:

    PHP Code:
    $STH->setFetchMode(PDO::FETCH_ASSOC); 
    Could somebody kindly explain, or provide resources that explain:
    a) Why we are setting a fetch mode (and what the differences are) / why we need to do this; and
    b) What is with the syntax PDO::FETCH_ASSOC ? I guess this is more of a general OOP question, but I (think) it's to do with classes. When / why is it different to calling a property using -> to :: .

    Many thanks

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,405
    Mentioned
    45 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by adamcoppard View Post
    a) Why we are setting a fetch mode (and what the differences are) / why we need to do this
    Setting the fetch mode on a PDOStatement object determines what format your results will be returned in when you call $stmt->fetch(). You can find a full list of the options here: www.php.net/manual/en/pdo.constants.php, but some of the more commonly used options are PDO::FETCH_ASSOC which returns the results as an associative array (i.e. with column names as array keys), PDO::FETCH_NUM which returns a numbered array, and PDO::FETCH_CLASS which will return each row as an instance of a class that you specify.

    Quote Originally Posted by adamcoppard View Post
    b) What is with the syntax PDO::FETCH_ASSOC ? I guess this is more of a general OOP question, but I (think) it's to do with classes. When / why is it different to calling a property using -> to :: .
    PDO::FETCH_ASSOC is a class constant. You call it directly on the class it belongs to, rather than an instance of the class, and they are defined with a class like this:
    PHP Code:
    class PDO {
        const 
    FETCH_ASSOC 2;

    Class constants are useful for passing options into a class method. If the value ever changes in future (from 2 to 7, for example), your code won't break because you used the constant that represents the value you want.
    Last edited by fretburner; Jul 14, 2013 at 12:02. Reason: Fix broken link


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •