duanli9001 2015-06-16 04:28
浏览 17
已采纳

PHP数据对象(PDO)示例

I'm fairly new to object oriented programming in php, I just wrote the following script to create a connection using PDO and run a simple Select Query. It works fine, i just need to know if i have done it right! (need to know the best practices i'm missing).

<?php
class Connection
{
    protected $host = "localhost";
    protected $username = "admin";
    protected $password = "admin";  
    protected $database = "thedatabase";
    protected $dsn;
    protected $dbh;
    protected $opt = array(PDO::ATTR_ERRMODE=> PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE=> PDO::FETCH_ASSOC);
    protected $error_found = false;
    protected $error_message;

    function __construct()
    {
        $this->dsn = "mysql:host=$this->host;dbname=$this->database;charset=utf8";
        try
        {
            $this->dbh = new PDO($this->dsn, $this->username, $this->password, $this->opt);
        }
        catch (PDOException $e)
        {
            $this->error_message = $e->getMessage();
            $this->error_found = true;
        }
    }
    public function closeConnection()
    {
        $this->dbh = null;
    }
    public function errorsFound()
    {
        if ($this->error_found == true) 
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public function showError()
    {
        return $this->error_message;
    }
}

class Model extends connection
{
    public function select()
    {
        $sth = $this->dbh->query("SELECT * FROM `users`");
        $sth->setFetchMode(PDO::FETCH_ASSOC);
        while($row = $sth->fetch())
        {
            echo $row['username']."
";
            echo $row['password']."
";           
        }
    }
}

$connection = new Connection;
if ($connection->errorsFound()==true) 
{
    $error_messages = "Error: ".$connection->showError();
    echo $error_messages;
    $connection->closeConnection(); 
}
else
{
    $model = new Model;

    $model->select();
    $connection->closeConnection();
}
?>
  • 写回答

1条回答 默认 最新

  • dongwei1234 2015-06-16 04:38
    关注

    It looks alright for a basic implementation, beside that you shouldn't echo something inside a class.

    If you want see a well implemented solution, have a look into eloquent created by taylor otwell. That should give you heaps of ideas how to improve your code.

    https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Connection.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 复现论文:matlab仿真代码编写
  • ¥15 esp32驱动GC9A01循环播放视频
  • ¥15 惠普360g9的最新bios
  • ¥30 这个功能用什么软件发合适?
  • ¥60 微信小程序,取消订单,偶尔订单没有改变状态
  • ¥15 用pytorch实现PPO算法
  • ¥15 关于调制信号的星座图?
  • ¥30 前端传参时,后端接收不到参数
  • ¥15 这是有什么问题吗,我检查许可证了但是显示有呢
  • ¥15 机器学习预测遇到的目标函数问题