制作抽象的pdo类

时间:2014-09-25 07:18:41

标签: php mysql pdo

我只是从mysql_ *切换到PDO,因为我读到将来会删除mysql_ *现在我不知道将当前的类抽象为PDO的插入,更新和删除操作,也许是一些可以指出我如何将其转换为基于PDO的?

这是我的连接类,用于处理所有连接和其他相关功能(我已经制作了这个PDO,因此没有问题)

<?php
require_once(folder.ds."constants.php");

class MySQLDatabase {

    private $dbh;
    private $host = DB_SERVER;
    private $dbname = DB_NAME;

    private $stmt;
    public $query_terakhir;
    public $error_text;

    function __construct(){
        $this->open_connection();
    }

    public function open_connection(){
        $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,DB_USER,DB_PASS,$options);
        }
        catch(PDOException $e) {
            date_default_timezone_set('Asia/Jakarta');
            $dt = time();
            $waktu = strftime("%Y-%m-%d %H:%M:%S", $dt);
            $log = array_shift(debug_backtrace());
            file_put_contents('PDOErrors.txt',$waktu. ": " .$e->getMessage(). ": " .$log['file']. ": line " .$log['line']. "\n", FILE_APPEND);
        }
    }

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

    public function bind($param, $value, $type = null){
        if (is_null($type)) {
            switch (true) {
                case is_int($value):
                    $type = PDO::PARAM_INT;
                    break;
                case is_bool($value):
                    $type = PDO::PARAM_BOOL;
                    break;
                case is_null($value):
                    $type = PDO::PARAM_NULL;
                    break;
                default:
                    $type = PDO::PARAM_STR;
            }
        }
        $this->stmt->bindValue($param, $value, $type);
    }

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

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

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

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

    public function lastInsertId(){
        return $this->dbh->lastInsertId();
    }

    public function beginTransaction(){
        return $this->dbh->beginTransaction();
    }

    public function endTransaction(){
        return $this->dbh->commit();
    }

    public function cancelTransaction(){
        return $this->dbh->rollBack();
    }

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

$database = new MySQLDatabase();

?>

这是我的课程之一,帮助我保存(创建或更新),删除和其他人,使用此类我只需要更改$ nama_tabel表名,$ db_fields表示我的表字段和公共$ xxxxx与我的表字段匹配,创建,更新和删除功能可以完美地工作......

但是对于pdo我只是无法弄清楚如何使用与上面相同的方法使其适用于创建,更新和删除....

<?php
require_once('database.php');

class staff{
    public static $nama_tabel="staff";
    protected static $db_fields = array('id','name','job');

    public $id;
    public $name;
    public $job;

    private function has_attribute($attribute){
        $object_var = $this->attributes();
        return array_key_exists($attribute,$object_var);
    }

    protected function attributes(){
        $attributes = array();
        foreach(self::$db_fields as $field){
            if(property_exists($this, $field)){
                $attributes[$field] = $this->$field;
            }
        }
        return $attributes;
    }

    protected function sanitized_attributes(){
        global $database;
        $clean_attributes = array();
        foreach($this->attributes() as $key => $value){
            $clean_attributes[$key] = $database->escape_value($value);
        }
        return $clean_attributes;
    }

    public function create(){
        global $database;
        $attributes = $this->sanitized_attributes();

        $sql = "INSERT INTO " .self::$nama_tabel." (" ;
        $sql .= join(", ", array_keys($attributes));
        $sql .=")VALUES('";
        $sql .= join("', '", array_values($attributes));
        $sql .= "')";
        if($database->query($sql)){
            $this->id_kategori = $database->insert_id();
            return true;
        }else{
            return false;
        }
    }

    public function update(){
        global $database;
        $attributes = $this->sanitized_attributes();
        $attribute_pairs = array();
        foreach($attributes as $key => $value){
            $attribute_pairs[] = "{$key}='{$value}'";
        }

        $sql ="UPDATE " .self::$nama_tabel." SET ";
        $sql .= join(", ", $attribute_pairs);
        $sql .=" WHERE id=" . $database->escape_value($this->id);
        $database->query($sql);

        return($database->affected_rows() == 1) ? true : false;
    }

    public function delete(){
        global $database;

        $sql = "DELETE FROM " .self::$nama_tabel;
        $sql .= " WHERE id=". $database->escape_value($this->id);
        $sql .= " LIMIT 1";
        $database->query($sql);

        if(!empty($this->gambar)){
            $target = website .ds. $this->upload_dir .ds. $this->gambar;
            unlink($target);
        }

        return($database->affected_rows() == 1) ? true : false;
    }



}

?>

更新:这是我从GolezTrol的更新函数调整后创建函数的方法,但是不插入值而是插入name =:name和content =:content等等 更新:已经修好了!这是正确的

public function create(){
    global $database;
    $attributes = $this->attributes();

    $attribute_pairs = array();
    foreach($attributes as $key => $value){
        $attribute_pairs[] = ":{$key}";
    }

    $sql = "INSERT INTO " .self::$nama_tabel." (" ;
    $sql .= join(", ", array_keys($attributes));
    $sql .=")VALUES(";
    $sql .= join(", ", $attribute_pairs);
    $sql .= ")";

    $database->query($sql);

    foreach($attributes as $key => $value){
        $database->bind(":$key", $value);
    }

    if($database->execute()){
        $this->id = $database->lastInsertId();
        return true;
    }else{
        return false;
    }
}

第二次更新:我在while循环操作中经历了一些奇怪的事情,我在做的时候和内部我检查这个字段id是否与我的其他表id相等然后我将显示id name字段...并且它显示,但是停止我的while循环,所以我只循环获得1行(它应该显示40行)

$database->query($sql_tampil);
$database->execute();
while($row = $database->fetch()){
   $output = "<tr>";
        if(!empty($row['id']))

            $output .="<td><a data-toggle=\"tooltip\" data-placement=\"top\" 
                            title=\"Tekan untuk mengubah informasi kegiatan ini\" 
                            href=\"ubah_cuprimer.php?cu={$row['id']}\"
                            >{$row['id']}</a></td>";
        else
            $output .="<td>-</td>";

        if(!empty($row['name'])){
            $y = "";
            $x = $row['name'];
            if(strlen($x)<=40)
                $y = $x;
            else
                $y=substr($x,0,40) . '...';

            $output .="<td><a data-toggle=\"tooltip\" data-placement=\"top\" 
                            title=\"{$row['name']}\" 
                             href=\"ubah_cuprimer.php?cu={$row['id']}\"
                        > {$y} </td>";
        }else
            $output .="<td>-</td>";

        $wilayah_cuprimer->id = $row['wilayah'];
        $sel_kategori = $wilayah_cuprimer->get_subject_by_id();
        if(!empty($sel_kategori))
           $output .="<td><a href=\"#\" class=\"modal1\"
                            data-toggle=\"tooltip\" data-placement=\"top\" 
                            title=\"Tekan untuk mengubah kategori artikel ini\"  
                            name={$row['id']}>{$sel_kategori['name']}</a></td>";
        else
           $output .="<td><a href=\"#\" class=\"modal1\"
                            data-toggle=\"tooltip\" data-placement=\"top\" 
                            title=\"Tekan untuk mengubah kategori artikel ini\"  
                            name={$row['id']}>Tidak masuk wilayah</a></td>";

        if(!empty($row['content'])){
            $content = html_entity_decode($row['content']);
            $content = strip_tags($content);
            $z = "";
            $v = $content;
            if(strlen($v)<=40)
                $z = $v;
            else
                $z=substr($v,0,40) . '...';

            $output .="<td><a data-toggle=\"tooltip\" data-placement=\"top\" 
                            title=\"{$content}\" 
                             href=\"ubah_cuprimer.php?cu={$row['id']}\"
                        >{$z}</a> </td>";
        }else
            $output .="<td>-</td>";


        if(!empty($row['tanggal']))
            $output .="<td>{$row['tanggal']}</td>";
        else
            $output .="<td>-</td>";

        if(!empty($row['id']))
            $output  .="<td><button class=\"btn btn-default modal2\"
                            name=\"{$row['id']}\" 
                            data-toggle=\"tooltip\" data-placement=\"top\" 
                            title=\"Tekan untuk menghapus layanan ini\" ><span 
                            class=\"glyphicon glyphicon-trash\"></span></button></td>";
        else
            $output .="<td>-</td>";

    $output .="</tr>";

   echo $output;
}

这是我的$ wilayah_cuprimer-&gt; get_subject_by_id();功能

public function get_subject_by_id(){
    global $database;
    $sql = "SELECT * ";
    $sql .= "FROM ".self::$nama_tabel;
    $sql .= " WHERE id = :id" ;
    $sql .= " LIMIT 1";

    $database->query($sql);
    $database->bind(":id",$this->id);
    $database->execute();
    $array = $database->fetch();

    return $array; 
}

1 个答案:

答案 0 :(得分:1)

很高兴您转换到PDO。现在最好这样做,然后发现有一天你无法升级PHP,因为它会破坏你的应用程序。

据我所知,$database->query($sql);只准备一份声明。这是第一步,但在此之后你也需要执行它。您已经拥有$database->execute()方法,但不要在插入,更新和删除函数中调用它。

除了这个问题之外,如果您也使用绑定参数进行更新,并将转义字符串留给数据库,那就更好了。

完整地测试你的课程很困难,但我希望这会给你一些想法。我添加了评论来描述这些步骤。

public function update(){
    global $database;

    // Don't need 'clean' attributes if you bind them as parameters.
    // Any conversion you want to support is better added in $database->bind,
    // but you don't need, for instance, to escape strings.
    $attributes = $this->attributes();

    // Place holders for the parameters. `:ParamName` marks the spot.
    $attribute_pairs = array();
    foreach($attributes as $key => $value){
        $attribute_pairs[] = "{$key}=:{$key}";
    }

    $sql ="UPDATE " .self::$nama_tabel." SET " .
          join(", ", $attribute_pairs) .
          " WHERE id = :UPDATE_ID";
    $database->query($sql);

    // Bind the ID to update.
    $database->bind(':UPDATE_ID', $this->id);

    // Bind other attributes.
    foreach($attributes as $key => $value){
        $database->bind(":$key", $value);
    }

    // Execute the statement.
    $database->execute();

    // Return affected rows. Note that ->execute also returns false on failure.
    return($database->affected_rows() == 1) ? true : false;
}