具有数据库连接的对象

时间:2014-10-17 04:24:33

标签: php oop pdo

我有一个:

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();
    }
}

我正在创造这样的人:

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

这是我的数据库类

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

我经常收到此消息

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

我想确认这种方法是否正确。在构造函数中调用数据库? 我怎么知道创建的人是否存在(我的意思是存在于数据库中)

我应该这样做吗?

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

谢谢

0 个答案:

没有答案