0

I have a:

class Person 
{
    public $data;
    public function __construct($name) {
        $database = new Database;

        $database->prepare('SELECT * FROM persons where name = :name');
        $database->bindParam(':name', $name);
        $database->execute();

        $this->data = $database->fetch();
    }
}

and i´m creating persons like this:

$jim = new Person('Jim');
$mike = new Person('Mike');

and this is my database class

class Database
{
    private $host = 'localhost';
    private $user = 'test';
    private $pass = '123';
    private $dbname = 'test';

    private $dbh;
    private $error;

    private $stmt;

    public function __construct()
    {
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;

        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        }

        catch(PDOException $e){
            $this->error = $e->getMessage();
            echo $this->error;
        }
    }

    public function prepare($query)
    {
            $this->stmt = $this->dbh->prepare($query);
    }

    public function bindParam($key, $val)
    {
        $this->stmt->bindParam($key, $val);
    }

    public function execute()
    {
            $this->stmt->execute();
    }


    public function fetch()
    {
        return $this->stmt->fetch(PDO::FETCH_ASSOC);
    }
}

I´m getting this message very often

Warning:  PDO::__construct(): MySQL server has gone away

I want to confirm if this approach is correct. calling the database in the constructor? How can i know if the created person exists (i mean exist in the database)

should i do something like this?

$jim = new Person('Jim');
if($jim->data) {
    echo 'person exists in the db';
}

thank you

handsome
  • 2,335
  • 7
  • 45
  • 73
  • You can just go and check in the MySQL database. – Spencer Wieczorek Oct 17 '14 at 04:26
  • 1
    I would highly recommend creating your `Database` outside the `Person` and use [Dependency Injection](http://stackoverflow.com/questions/10064970/php-dependency-injection) to give DB access to your domain entities. – Crackertastic Oct 17 '14 at 04:27
  • Mate to do a instantization of the Database object in each class that possibly need to interact with the database will be application killer approach. Please follow the advice of @Crackertastic – Antoan Milkov Oct 17 '14 at 06:00

0 Answers0