0

Here is my code

<?php
class db extends PDO {
    private $error; private $sql; private $bind; private $errorCallbackFunction; private $errorMsgFormat;

    public function __construct($dsn, $user="", $passwd="") {
        $options = array(
            PDO::ATTR_PERSISTENT => true, 
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        try {
            parent::__construct($dsn, $user, $passwd, $options);
        } catch (PDOException $e) {
            $this->error = $e->getMessage();
        }
    }

But that line $this->error = $e->getMessage(); is showing error like this

Warning: Creating default object from empty value in C:\Program Files (x86)\Ampps\www\blog\library\class-database.php on line 14

I have created the code like this

$db = new db("mysql:host=localhost;port=3306;dbname=".$dbname, $dbusername, $dbpassword);

and for testing other value were correct except $dbname as i want to show user that they inserted incorrect database details.

user3697137
  • 23
  • 1
  • 4
  • @Wesley i guess it is not duplicate with that post . – user3697137 Jun 02 '14 at 05:14
  • 1
    Yep you are right, I'm not sure what's the matter with this code. I don't necessarily think it's the best idea to extend PDO though... – Wesley Murch Jun 02 '14 at 05:18
  • @Wesley Murch actually this is the php wrapper class code from this http://www.imavex.com/php-pdo-wrapper-class/ . I used as it is easy to update and prevent from sql injection as it uses bind . But now it is showing warning..and my project is entirely based with that wrapper class.i don't know what should i do :( . – user3697137 Jun 02 '14 at 05:26
  • @user3697137 does $error needs to be a property, I would make it a function variable. – meda Jun 02 '14 at 05:52

1 Answers1

-1

I'm trying to find documentation for this, but basically it seems that after the exception is thrown in the reference to $this is set to null. For example if you print_r($this) just before $this->error you'll get nothing.

The best I can come up with in the way of an explanation for this is the source code for the PDO extension which seems to set the object to null if there's an error.

Regardless of that – it's bad practice to conceal (catch) an exception in a constructor which could lead to an invalid state. I'd recommend simply removing the try catch from within the constructor and put it wherever you instantiate the object (which should probably only be once in your application). Then you can deal with that exception appropriately (most likely exit the application).

Alternatively, you could encapsulate the PDO class rather than extending it.

Also, this particular code snipped doesn't inspire a great deal of confidence in the wrapper you're using. You may like to take a look at a fully fledged ORM like doctrine or propel.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
thexacre
  • 702
  • 4
  • 9