CRUD -更新MySQL数据库时出错


CRUD - Error When Updating MySQL Database

我正在学习如何编写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();
?>

首先,你的查询可能会因为这个

而失败
$sql  = "UPDATE ".static::$table_name." SET ";

是无效的。试一试:

$sql  = "UPDATE ".self::$table_name." SET ";