[英]update a single field in the mysql while retaining the rest of the values in the other fields
您好,我正在嘗試更新數據庫中的單個字段,並將其余值保留在其他字段中,但它會繼續刪除其余字段。.不確定我在做什么錯嗎? 這是一些代碼
if(isset($_POST['submit_approve'])) {
$comment = new Comment();
// $comment->author = $author;
// $comment->blog_id = $blog_id;
// $comment->body = $body;
// $comment->created =$created;
$comment->visible = $_POST['visible'];
$comment->id = $_GET['id'];
if($comment->update()) {
} else {
}
}
這就是我正在嘗試更新的內容,如您所見,我只想更新表中的可見字段,而我已經評論了另外4個字段,因此您可以看到..
這是功能
public function update() {
global $database;
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $database->escape_value($this->id);
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
}
誰能看到我在哪里出錯? 干杯
有兩種解決方法:
檢索原始行,修改適當的字段,然后保存/更新。
限制要更新的字段,可能是通過將要更新的字段作為參數傳遞給方法。
對於某些項目,最有可能未在foreach循環中設置$ value(false,null或''),但是無論如何您都將其添加到$ attribute_pairs數組中。 然后在更新中,您將全部加入。 可能最簡單的事情是這樣的:
if ( ($value != null) && ($value != false) && ($value != '') ) {
$attribute_pairs[] = "{$key}='{$value}'";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.