gpt4 book ai didi

php - 在 PHP 中使用关联数组构造 UPDATE 语句

转载 作者:行者123 更新时间:2023-11-29 00:38:34 24 4
gpt4 key购买 nike

在 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)

最佳答案

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

关于php - 在 PHP 中使用关联数组构造 UPDATE 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13269067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com