Hi,

Any tips on how I can make a smarter function? I have recently begun oop, so Im not allways sure if I do things in a "bad way" - both the amount of code, and the performance.

Any advice on this piece is appreciated:

class get_page_info 
{
public $id; 
public $h_id;   
public $titel;  
public $link;   
public $url;    
public $publiceret; 
public $indhold;    
public $meta_desc;  
public $meta_key;   
public $oprettet;   
public $oprettet_af;    
public $opdateret;  
public $opdateret_af;   
public $indekseret; 
public $beskyttet;  
public $layout; 

public function __construct( $id )
{
    // Database object :
    $database           = new PDO_CONNECTION(DSN, USER, PASS);

    // Prepare query :                  
    $stmt               = $database->prepare("SELECT id, h_id, titel, link, url, publiceret, indhold, meta_desc, meta_key, oprettet,
                        oprettet_af, opdateret, opdateret_af, indekseret, beskyttet, layout 
                        FROM pages 
                        WHERE SHA1(id) = :id");
    // Execute :
    $stmt->execute( array( ':id' => $id ) );
    // Fetch :
    while( $data = $stmt->fetch( PDO::FETCH_ASSOC ))
    {
        $this->id           = $data['id'];
        $this->h_id         = $data['h_id'];
        $this->titel        = $data['titel'];
        $this->link         = $data['link'];
        $this->url          = $data['url'];
        $this->publiceret   = $data['publiceret'];
        $this->indhold      = $data['indhold'];
        $this->meta_desc    = $data['meta_desc'];
        $this->meta_key     = $data['meta_key'];
        $this->oprettet     = $data['oprettet'];
        $this->oprettet_af  = $data['oprettet_af'];
        $this->opdateret    = $data['opdateret'];
        $this->opdateret_af = $data['opdateret_af'];
        $this->indekseret   = $data['indekseret'];
        $this->beskyttet    = $data['beskyttet'];
        $this->layout       = $data['layout'];
    }
}
}

How can I simply use $stmt->fetchAll() - How do i get the data outside the class, if i do that? Would be nice to spare all the properties and the while loop...

Member Avatar for diafol

I'd have a separate db class and pass that as a paramter to the page class (like "dependency injection").

You probably don't need individual items?

class Page 
{
    private $db;

    public function __construct( $db )
    {
        $this->db = $db;
        $this->id = $id;
    }

    public function getPage($id)
    {
        //you should check that $id is of a fixed length (if SHA1) or whatever before proceeding

        $stmt = $this->db->prepare("SELECT id, h_id, titel, link, url, publiceret, indhold, meta_desc, meta_key, oprettet,
                            oprettet_af, opdateret, opdateret_af, indekseret, beskyttet, layout 
                            FROM pages 
                            WHERE SHA1(id) = :id LIMIT 1");
        // Execute :
        $stmt->execute( array( ':id' => $id ) );
        // Fetch :
        if($data = $stmt->fetch( PDO::FETCH_ASSOC ))
        {
            return $data;
        }else{
            //do something for probs here - you could even enclose this in a try/catch/throw
            return false;
        }
    }
}

Typical usage:

$db = new DB; //depending on the DB class you build
$page = new Page($db);
$id = '902ba3cda1883801594b6e1b452790cc53948fda'; //from your url or whatever you're using
if($pageData = $page->getPage($id)){
    echo $pageData['titel'];
    //success code - if page found
}else{
    echo "Page not found";
}

Not tested, just off top of my head. BTW - any reason why you're hashing the ID?

Since you're building a class, why not use fetchObject to return an object instead of an associative array.

@diafol :
Thank you - Exactly what I had in mind - just short of experience to actually implement it..

Note:

Overall questions regarding PDO:
1) Exactly WHY and/or WHEN should I prefer to use it? ( There are so many opinions on this topic, and surely a lot more here.. - But still I need to clarify why and when to use it over mysqli )
2) My PDO connection class - Is that made in an "okay" way :

Class PDO_CONNECTION extends PDO {

public static function exception_handler( $exception ) {
// Exception :
      die( 'Uventet fejl: '. $exception->getMessage() );
}

public function __construct( $DSN, $USER = '', $PASS = '', $DRIVER_OPTIONS = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) ) {

// FORANDRER MIDLERTIDIGT EXCEPTION HANDLER IMENS DER OPRETTES ET PDO OBJECT :
set_exception_handler( array(__CLASS__, 'exception_handler') );
// OPRET PDO OBJECT FRA PARENT PDO CLASS :
parent::__construct( $DSN, $USER, $PASS, $DRIVER_OPTIONS );

// SÆT EXCEPTION HANDLER TILBAGE TIL DEN STATUS DEN HAVDE FØR :
restore_exception_handler();
    }
}

3) When I inserted PDO::ATTR_PERSISTENT into the options array, I every now and then get this errror

"MySQL server has gone away" etc etc...

I read by removing it, I could remove that error, (since Im not sure how to keep it AND remove the error..) - So I did that. BUT, wouldnt I gain on performance by having a persistent database connection? One of the reasons I wanted to use PDO...

4) Can I gain performance/is it better practice to declare the type of bound parameters (int, string..), instaed of execute the array with values - Is that the "intended approach"?

I hope you can put some lights on these thoughts, as I can make it work all fine, but hate when Im not 100% sure WHY im doing it...

Best, Klemme

@pritaeas,

Thank you, that leaves one question tjecked :-)

1) As for why/when. The advantage of PDO over MySQLi is that it is very easy to switch over to another type of database (assuming standard compatible queries).

2) Not how I'd do it, but it's a good start.

4) Not sure. I suggest you do a speed comparison and find out ;) Then tell me, so I know it too. Better, IMO yes. As you specifically declare a column's type. That way you can get a better error for trying to put a string into an int column.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.