我正在学习如何编写php以及我正在研究CRUD。到目前为止,我已经使用了Create和Delete方法,但对于我的生活,我无法让Update工作。我错过了一些完全明显的东西吗?提前谢谢。
在我的User类中,我有以下内容(此处仅包含相关方法):
protected static $table_name="users";
protected static $db_fields = array('id', 'f_name');
public $id;
public $f_name;
public static function find_by_id($id=0) {
global $db;
$result_array = self::find_by_sql("SELECT * FROM ".static::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
protected function attributes() {
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $db;
$clean_attributes = array();
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $db->escape_value($value);
}
return $clean_attibutes;
}
public function update() {
global $db;
$attributes = $this->attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attibute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $db->escape_value($this->id);
$db->query($sql);
if ($db->affected_rows() == 1) {
echo "Yes!";
} else {
echo "No!";
}
}
在我的html文件中,我只是:
<?php
$user = User::find_by_id(1);
$user->f_name = "UpdatedUser";
$user->update();
?>
答案 0 :(得分:0)
好吧,你的查询可能因此而失败
$sql = "UPDATE ".static::$table_name." SET ";
无效。尝试:
$sql = "UPDATE ".self::$table_name." SET ";