2014-09-25 69 views
0

我只是从mysql_ *切换到PDO,因为我读了mysql_ *将在未来被删除,现在我不知道要插入,更新抽象我当前类和删除操作PDO ,也许有人可以指出如何将它翻译成基于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(); 

?> 

,这里是我班的一个帮助我不要保存(创建或更新),删除等,这个类我只需要改变我的表的字段和公共$ XXXXX $ nama_tabel对表的名称,$ db_fields我的表中的字段匹配和创建,更新和删除功能工作完全...

但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,但不插入值,而不是之后创建函数插入它的名字=:名称和含量=:内容等 更新:它已经固定!这里是正确的

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

月2日更新:我遇到了一些奇怪的事情在同时,在那里我做的,而与同时里面我检查该字段ID与我的其他表ID相等的,那么我会告诉循环操作该ID名称字段......这显示,但回采我while循环,所以我只得到1行while循环(它应该显示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-> 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

很好,你过渡到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; 
} 
+0

哇感谢你的帮助,它可以很好地用于更新的方法,但是当我试图实施创造功能,它GVE输入喜欢的名字我的领域则表现出表“NAME =:名称”你可以点我在哪里错了? (我更新了我的问题以显示我的插入方法) – PUCUK 2014-09-25 08:48:43

+0

插入语法的语法略有不同,您可以写入INSERT INTO TABLE(Field1,Field2)VALUES(Value1,Value2)'。因此,占位符'Field1 =:Field1'不起作用。幸运的是,MySQL知道另一种插入语法,即INSERT INTO Table SET Field1 = Value1,Field2 = Value2'。这与更新语法非常相似,因此如果使用该语法,则可以使用几乎相同的代码。请参阅[MySQL插入语法](http://dev.mysql.com/doc/refman/5.6/en/insert。html) – GolezTrol 2014-09-25 09:55:40

+0

哦好吧我已经修复了它......现在我正在改变while循环但遇到一些奇怪的事情......我做了一个while循环和while循环内我检查这个行位置字段ID是否与ID相等在我的位置表中,它会显示位置名称并显示!但之后,我的while循环停止...所以它只显示1行数据...我将在后 – PUCUK 2014-09-25 10:16:36