2014-09-25 24 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