public function update($id, $table, $data, $exclude = array()){
$query = "UPDATE $table SET";
$fields = $values = array();
if(!is_array($exclude)) $exclude = array($exclude);
foreach(array_keys($data) as $key) {
if(!in_array($key, $exclude)) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
$fields = implode(" ", $fields);
$values = implode(" ", $values);
$query .= $fields . "=" . $values . ",";
}
$query = $query . "WHERE id = '".$id."' ";
if(!$this->db->query($query)){
echo "Something wrong with query ";
}
else{
echo "successfully updated";
}
}
遇到错误更新的数据动态
Fatal error: [] operator not supported for strings
从中工作的附加功能,调整了代码。希望在不使用变量的情况下动态更新字段和值,例如$ _POST ['address']。
$query .= $fields . "=" . $values . ", ";
似乎没有工作。不知道是什么导致了错误:致命错误:[]运算符不支持字符串。如何在sql查询中插入field = value?
你implode数组内foreach和更新在同一个变量,所以他们改变为字符串。 '$ fields = implode(“”,$ fields);',在foreach之外执行,或者在foreach开头初始化'$ fields = $ values = array();'。 –
为什么人们帮助你,如果你不采取建议? –