在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 :(得分:1)
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:
答案 1 :(得分:0)
我认为一个简单的解决方案是使用implode()
使用'AND'作为分隔符:
$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 Framework在Db版本的框架中有一个非常好的both组件。