Blog
Update a Password for a Single MySQL User in a Table Row using CodeIgniter with Model, Controller, and View Code Examples
Posted on July 2, 2015 in CodeIgniter, MVC, MySQL, PHP by Matt Jennings
View
<?php
class UserDashboardModel extends CI_Model
{
public function update_single_password($post_data, $user_id)
{
$sec_password = substr(md5($post_data['password']), 0, -2);
$this->db->query("UPDATE users SET password = '$sec_password', updated_at = NOW() WHERE id = $user_id");
}
}
?>
Controller
<?php
class UserDashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load the UserDashboardModel on all pages
$this->load->model('UserDashboardModel');
$this->output->enable_profiler();
}
public function executeupdateuserpassword($user_id)
{
// Load the form helper
$this->load->helper('form');
// Load the form_validation library
$this->load->library('form_validation');
$this->form_validation->set_rules('password', '<strong><em>password</em></strong>', 'required|xss_clean|trim|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confirm_password', '<strong><em>password confirmation</em></strong>', 'required|xss_clean|trim|matches[password]');
// If there are form validation errors
if($this->form_validation->run() == FALSE)
{
// Set registration errors as a
// flash data variable
$this->session->set_flashdata('admin_user_add_errors', validation_errors());
redirect(base_url() . 'users/edit/' . $user_id);
}
else
{
// Set user first/last name as variable
$update_success = "<p><strong>The password of User ID $user_id has been updated.</strong></p>";
$this->session->set_flashdata('success_message', $update_success);
$this->UserDashboardModel->update_single_password($this->input->post(NULL, TRUE), $user_id);
redirect(base_url() . 'users/edit/' . $user_id);
}
}
}
?>
View
<?php
// If the admin sessin variable DOESN'T exist
// redirect to home page
if(!$this->session->userdata('admin_session'))
{
redirect(base_url());
}
?>
<h3>Change Password</h3>
<div class="error">
<?php
echo $this->session->flashdata('admin_user_add_errors');
?>
</div>
<div class="success">
<?php
echo $this->session->flashdata('success_message');
?>
</div>
<form action="<?php echo base_url() . 'users/pw/process/' . $show_single_user['id']; ?>" method="post" class="side-by-side-form">
<input type="hidden" name="user_pw_update"/>
<p>
<label for="password">Password:</label><br />
<input type="password" name="password"/>
</p>
<p>
<label for="confirm_password">Confirm Password:</label><br />
<input type="password" name="confirm_password"/>
</p>
<p> </p>
<p>
<input type="submit" value="Update"/>
</p>
</form>
Leave a Reply