这是我网站的用户模型。
class User_model extends CI_Model {
public $user_first_name;
public $user_last_name;
public $user_email;
public $user_password;
public $ur_id;
public function insert_entry()
{
$password = password_hash($this->input->post('user_password'), PASSWORD_DEFAULT);
$this->user_first_name = $this->input->post('user_first_name');
$this->user_last_name = $this->input->post('user_last_name');
$this->user_email = $this->input->post('user_email');
$this->user_password = $password;
$this->ur_id = $this->input->post('ur_id');
$this->db->insert('user', $this);
return $this->db->affected_rows();
}
public function update_entry()
{
$this->user_first_name = $this->input->post('user_first_name');
$this->user_last_name = $this->input->post('user_last_name');
$this->user_email = $this->input->post('user_email');
$this->ur_id = $this->input->post('ur_id');
$this->db->update('user', $this, array('user_id' => $this->input->post('user_id')));
return $this->db->affected_rows();
}
}
正如您在代码中看到的那样,我不会在编辑时更新密码。所以我已将其从update_entry()
函数中删除了。
当我调用update_entry()
函数时,它会返回以下查询。
UPDATE `user` SET `user_first_name` = 'Ruwan', `user_last_name` = 'Thilanka', `user_email` = 'ruwan1@example.com', `user_password` = NULL, `ur_id` = '2'
WHERE `user_id` = '7'
正如您所见,它会自动将'user_password' = NULL
添加到查询中。
为什么它是自动添加的,即使我没有在update_entry()
上提到它。我怎么删除它? (请注意,它应该在insert_entry()
函数中。
答案 0 :(得分:4)
为什么要更新update_query()中的用户ID。
好吧,我建议你在SQL查询中添加WHERE,在WHERE之后提供用户ID。然后更新用户表。
下面是我系统中运行的示例函数。你可能会发现它很有帮助。
确保我在数据库中使用的user_id字段名称相同,否则
使用您的用户ID字段进行更改。
public function update_entry()
{
$postedData = $this->input->post();
$userID = $postedData['user_id'];
$refinePostedData = array(
'your-field-name' => $postedData['user_first_name'],
'your-field-name' => $postedData['user_last_name'],
'your-field-name' => $postedData['user_email'],
);
if($refinePostedData!='')
{
$this->db->where("id", $userID);
$this->db->update("user", $refinePostedData);
return $this->db->affected_rows();
}
}
答案 1 :(得分:0)
这里我们使用unset()fn从'$ this'对象中删除'user_password'字段并将数据传递给update。
public function update_entry()
{
$this->user_first_name = $this->input->post('user_first_name');
$this->user_last_name = $this->input->post('user_last_name');
$this->user_email = $this->input->post('user_email');
$this->ur_id = $this->input->post('ur_id');
unset($this->user_password);
$this->db->update('user', $this, array('user_id' => $this->input->post('user_id')));
return $this->db->affected_rows();
}