2011-07-17 43 views
1

保存Zend_Db_Table_Row時是否可以讓ZF在一列上應用SQL函數?在Zend_Db_Table_Row :: save()上應用SQL函數

例如,如果$row->save()默認生成此SQL查詢:

UPDATE table SET field = ? WHERE id = ?; 

我想它會自動應用GeomFromText()功能在這個領域:

​​

感謝如何任何暗示用Zend_Db來做到這一點!

回答

1

我只是猜測,但你可以試試這個:

<?php 
class MyTable extends Zend_Db_Table_Abstract 
{ 
    protected $_name = 'my_table'; 

    public function update(array $data, $where) { 
     /** 
     * Build "col = ?" pairs for the statement, 
     * except for Zend_Db_Expr which is treated literally. 
     */ 
     $set = array(); 
     $i = 0; 
     foreach ($data as $col => $val) { 
      if ($val instanceof Zend_Db_Expr) { 
       $val = $val->__toString(); 
       unset($data[$col]); 
      } else { 
       if ($this->_db->supportsParameters('positional')) { 
        $val = ($col == 'field') ? 'GeomFromText(?)' : '?'; 
       } else { 
        if ($this->_db->supportsParameters('named')) { 
         unset($data[$col]); 
         $data[':col'.$i] = $val; 
         $val = ($col == 'field') ? 'GeomFromText(:col'.$i.')' : ':col'.$i; 
         $i++; 
        } else { 
         /** @see Zend_Db_Adapter_Exception */ 
         require_once 'Zend/Db/Adapter/Exception.php'; 
         throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding"); 
        } 
       } 
      } 
      $set[] = $this->_db->quoteIdentifier($col, true) . ' = ' . $val; 
     } 

     $where = $this->_whereExpr($where); 

     /** 
     * Build the UPDATE statement 
     */ 
     $sql = "UPDATE " 
      . $this->_db->quoteIdentifier($this->_name , true) 
      . ' SET ' . implode(', ', $set) 
      . (($where) ? " WHERE $where" : ''); 

     /** 
     * Execute the statement and return the number of affected rows 
     */ 
     if ($this->_db->supportsParameters('positional')) { 
      $stmt = $this->_db->query($sql, array_values($data)); 
     } else { 
      $stmt = $this->_db->query($sql, $data); 
     } 
     $result = $stmt->rowCount(); 
     return $result; 
    } 

    protected function _whereExpr($where) 
    { 
     if (empty($where)) { 
      return $where; 
     } 
     if (!is_array($where)) { 
      $where = array($where); 
     } 
     foreach ($where as $cond => &$term) { 
      // is $cond an int? (i.e. Not a condition) 
      if (is_int($cond)) { 
       // $term is the full condition 
       if ($term instanceof Zend_Db_Expr) { 
        $term = $term->__toString(); 
       } 
      } else { 
       // $cond is the condition with placeholder, 
       // and $term is quoted into the condition 
       $term = $this->quoteInto($cond, $term); 
      } 
      $term = '(' . $term . ')'; 
     } 

     $where = implode(' AND ', $where); 
     return $where; 
    } 
} 
?> 
+1

我不會推薦使用Zend_Db_Expr,因爲您可以從Zend_Db_Adapter_Abstract中的更新方法(我從中實際獲取此代碼)中看到它,它直觀地處理Zend_Db_Expr,爲sql注入留出空間。 –