2012-11-07 26 views
0

在PHP中使用關聯數組構造UPDATE語句的最佳方式是什麼?在PHP中使用關聯數組構造UPDATE語句

例如,說我有一個功能,像這樣:

/** 
* For update queries 
* 
* @param string $tableName Name of the table we're wanting to update. 
* @param array $values Associative array of columns/values to update. e.g. array('name' => 'John', 'age' => 29) 
* @param array $conditions Associative array of conditions. e.g. array('user_id' => 1) equates to "WHERE user_id = 1" 
*/ 
public function update($tableName, $values, $conditions = array()){ 
     //Construct SQL 
} 

到目前爲止,我已經能夠建立簡單UPDATE語句如:

UPDATE `myTableName` SET `name` = :name, `age` = :age WHERE `user_id` = :user_id 

現在我離開想知道:什麼是最好的方法來構建WHERE子句?我可以看看其他庫和代碼庫中是否有類似的實現?例如:我如何處理具有OR和AND和IN()等的WHERE子句的構造?

UPDATE example SET col = :val WHERE user_id = :user_id AND (age = :age OR name = :name) 
+0

這可能:[**我可以將一個數組綁定到一個狀況**](HTTP:// stackoverflow.com/questions/920353/php-pdo-can-i-bind-an-array-to-an-in-condition) –

回答

0

我認爲,一個簡單的解決辦法是用「AND」作爲分隔符使用implode()

$columnCArrayValues = array(1, 2, 3, 4); 
$conditions = array(
    'column_a = :column_a', 
    'column_b <> :column_b', 
    'column_c IN (' . implode(',', $columnCArrayValues) . ')' 
); 

// .. 

$where = '(' implode(') AND (', $conditions) . ')'; 
// result: (column_a = :column_a) AND (column_b <> :column_b) 
// AND (column_c IN (1,2,3,4)) 

另外,該Zend Frameworkboth版本的框架的一個非常好的Db組件。

0
public function update($tableName, $values, $conditions = array()) { 
    if (empty($values)) { 
     throw new Exception('Nothing to update'); 
    } 
    $valueStrings = array(); 
    foreach ($values as $name => $value) { 
     $valueStrings[] = $name . ' = :' . $name; 
    } 
    $conditionStrings = array(); 
    foreach ($conditions as $column => $value) { 
     $conditionString = $column; 
     $conditionString .= is_array($value) 
      ? ('IN ("' . implode('","', $value) . '")') 
      : (' = "' . $value . '"') 
     ; 
     $conditionStrings[] = $conditionString; 
    } 
    $sql = 'UPDATE ' . $tableName 
     . ' SET ' . implode(', ', $valueStrings) 
     . ' WHERE ' . implode(' AND ', $conditionStrings) 
    ; 
    // execute query 
} 

但實際上,你應該使用的是一個ORM:通過有益的

Doctrine 2: Update query with query builder