On my user table I have a column called code. If a user has clicked on the forgotten password link and enters in email and then clicks on submit. It then updates the code on to the database row matching the email.
I have another controller called Forgotten which handles the $code and editCode that works fine.
The problem I am having is I have tried a few times and will not edit/change password. I currently have removed non working code.
I need to be able to check make sure the $code = URI Segment 3 matches the code and email on that database row. And then allows me to update/change password.
Controller Reset
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Reset extends MX_Controller {
public function __construct() {
parent::__construct();
if ($this->user->hasPermissionAccess() == TRUE) {
$this->lang->load('admin/english', 'english');
$this->lang->load('admin/common/reset', 'english');
$this->load->library('settings');
$this->load->library('pagination');
$this->load->library('request');
$this->load->library('response');
$this->load->library('document');
$this->load->library('email');
} else {
redirect('admin/error');
}
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['heading_title'] = $this->lang->line('heading_title');
$data['text_password'] = $this->lang->line('text_password');
$data['entry_password'] = $this->lang->line('entry_password');
$data['entry_confirm'] = $this->lang->line('entry_confirm');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => '<i class="fa fa-home"></i>' .' '. $this->lang->line('text_home'),
'href' => site_url('common/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => $this->lang->line('heading_title'),
'href' => site_url('common/forgotten')
);
if (!empty($this->request->post['password'])) {
$data['password'] = $this->request->post['password'];
} else {
$data['password'] = '';
}
if (!empty($this->request->post['confirm_password'])) {
$data['confirm_password'] = $this->request->post['confirm_password'];
} else {
$data['confirm_password'] = '';
}
$data['action'] = site_url('admin/reset') .'/'. $this->uri->segment(3);
$data['cancel'] = site_url('admin/login');
$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password','required|trim|xss_clean|matches[confirm]|min_length[3]|max_length[25]');
$this->form_validation->set_rules('confirm_password', 'Password Confirmation', 'required|trim');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('common/reset', $data);
} else {
$this->load->model('admin/user/users_model');
$code = $this->uri->segment(3);
$user_info = $this->users_model->getUserByCode($code);
if($user_info) {
$this->load->model('admin/user/users_model');
$this->users_model->editUser($user_info['user_id'], $this->request->post, $data);
$this->session->set_flashdata('success', 'You have now updated your Password!');
redirect('admin');
return true;
} else {
$this->session->set_flashdata('error', 'Unable to submit changes. Please try again!');
redirect('admin');
return false;
}
}
}
}
Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users_model extends CI_Model {
public function addUser($data) {
$user_insert = array(
'user_group_id' => "10",
'username' => $data['username'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => $this->hash($data['password']),
'status' => $data['status'],
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user', $user_insert);
}
public function editUser($user_id, $data) {
$data['last_updated'] = mdate('%Y-%m-%d %H:%i:%s', now());
if (isset($data['password']) && $data['password']) {
$data['password'] = $this->hash($data['password']);
} else {
unset($data['password']);
}
$this->db->where('user_id', $user_id)->update('user', $data);
return $user_id;
}
public function getUserByCode($code) {
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "user`
WHERE code = '" . $this->db->escape($code) . "' AND code != ''");
return $query->row_array();
}
public function hash($password) {
$this->load->library('PasswordHash', array('iteration_count_log2' => 8, 'portable_hashes' => FALSE));
return $this->passwordhash->HashPassword($password);
}
public function editCode($email, $code) {
$this->db->where('email', $this->request->post['email']);
$this->db->set('code', $code);
$this->db->update($this->db->dbprefix . 'user');
}
}
I have been working hard at problem solving last half hour but have figured out why I need to do a couple of edit password separate from edit user and added get by code.
New controller and model methods down below for my resetting password. I still have a separate forgotten controller that handles the reset code
Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users_model extends CI_Model {
public function addUser($data) {
$user_insert = array(
'user_group_id' => "10",
'username' => $data['username'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => $this->hash($data['password']),
'status' => $data['status'],
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user', $user_insert);
}
public function editUser($user_id, $data) {
$data['last_updated'] = mdate('%Y-%m-%d %H:%i:%s', now());
if (isset($data['password']) && $data['password']) {
$data['password'] = $this->hash($data['password']);
} else {
unset($data['password']);
}
$this->db->where('user_id', $user_id)->update('user', $data);
return $user_id;
}
public function editPassword($user_id, $password) {
$data['password'] = $this->request->post['password'];
$this->db->query("UPDATE `" . $this->db->dbprefix . "user`
SET
password = " . $this->db->escape($this->hash($data['password'])) . ",
code = ''
WHERE
user_id = '" . (int)$user_id . "'");
}
public function hash($password) {
$this->load->library('PasswordHash', array('iteration_count_log2' => 8, 'portable_hashes' => FALSE));
return $this->passwordhash->HashPassword($password);
}
public function editCode($email, $code) {
$this->db->where('email', $this->request->post['email']);
$this->db->set('code', $code);
$this->db->update($this->db->dbprefix . 'user');
}
public function deleteUser($user_id) {
$this->db->where('user_id', $user_id);
$this->db->delete($this->db->dbprefix . 'user');
}
public function getUser($user_id) {
$query = $this->db->query("SELECT *, (SELECT ug.name FROM `" . $this->db->dbprefix . "user_group` ug WHERE ug.user_group_id = u.user_group_id) AS user_group FROM `" . $this->db->dbprefix . "user` u WHERE u.user_id = '" . (int)$user_id . "'");
return $query->row_array();
}
public function getUserByUsername($username) {
$query = $this->db->query("SELECT * FROM `" . $this->db->dbprefix . "user` WHERE username = ". $this->db->escape($username) ." ");
return $query->row();
}
public function getUserByCode($code) {
$query = $this->db->query("SELECT * FROM `" . $this->db->dbprefix . "user`
WHERE code = " . $this->db->escape($code) . " AND code != ''");
return $query->row_array();
}
public function getUsers() {
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'user');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
return true;
} else {
return false;
}
}
public function getTotalUsers() {
return $this->db->count_all('user');
}
public function getTotalUsersByGroupId($user_group_id) {
$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . $this->db->dbprefix . "user` WHERE user_group_id = '" . (int)$user_group_id . "'");
return $query->row_array('total');
}
public function getTotalUsersByEmail($email) {
$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . $this->db->dbprefix . "user` WHERE LCASE(email) = " . $this->db->escape($email) . " ");
return $query->row_array('total');
}
}
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Reset extends MX_Controller {
public function __construct() {
parent::__construct();
if ($this->user->hasPermissionAccess() == TRUE) {
$this->lang->load('admin/english', 'english');
$this->lang->load('admin/common/reset', 'english');
$this->load->library('settings');
$this->load->library('pagination');
$this->load->library('request');
$this->load->library('response');
$this->load->library('document');
$this->load->library('email');
} else {
redirect('admin/error');
}
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['heading_title'] = $this->lang->line('heading_title');
$data['text_password'] = $this->lang->line('text_password');
$data['entry_password'] = $this->lang->line('entry_password');
$data['entry_confirm'] = $this->lang->line('entry_confirm');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => '<i class="fa fa-home"></i>' .' '. $this->lang->line('text_home'),
'href' => site_url('common/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => $this->lang->line('heading_title'),
'href' => site_url('common/forgotten')
);
if (isset($this->request->post['password'])) {
$data['password'] = $this->request->post['password'];
} else {
$data['password'] = '';
}
$data['action'] = site_url('admin/reset') .'/'. $this->uri->segment(3);
$data['cancel'] = site_url('admin/login');
$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password','required|trim|xss_clean|matches[confirm_password]|min_length[3]|max_length[25]');
$this->form_validation->set_rules('confirm_password', 'Password Confirmation', 'required|trim');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('common/reset', $data);
} else {
$this->load->model('admin/user/users_model');
$code = $this->uri->segment(3);
$user_info = $this->users_model->getUserByCode($code);
if($user_info) {
$this->load->model('admin/user/users_model');
$this->users_model->editPassword($user_info['user_id'], $this->request->post['password']);
$this->session->set_flashdata('success', 'You have now updated your Password!');
redirect('admin');
return true;
} else {
$this->session->set_flashdata('error', 'Unable to submit changes. Please try again!');
redirect('admin');
return false;
}
}
}
}
Related
I want to create a login system in CodeIgniter.
I have this in my controller:
public function user_login_process()
{
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$username = $this->input->post('username');
$result = $this->login_database->read_user_information($username);
if ($result != false) {
$session_data = array(
'username' => $result[0]->username,
'email' => $result[0]->email,
);
$this->session->set_userdata('logged_in', $session_data);
if (isset($this->session->userdata['logged_in'])) {
if( $username="admin"){
$result1 = $this->login_database->read_admin_information($username);
if ($result1 != false) {
$session_data = array(
'username' => $result1[0]->username,
);
$this->session->set_userdata('admin', $session_data);
$this->load->view('admin_page');
}}}
else {
$this->load->view('home_page');
}}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
//}
I have this in my model:
public function login($data) {
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($username) {//Will read the data for loginn
$condition = "username =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
public function read_admin_information($username) {//Will read the data for loginn
$condition = "username =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
So I'm trying to create a session which differentiates a user if it is a normal or is admin(username=admin). The problem is that after I login like admin or not this always takes me to the admin page. What it should do: it should take me to the home_page if user is not admin but is logged in.
Have I done something wrong? I have read the session class of CI before I did this. Can someone help me to do this in right way? Thanks!
you are not comparing, you are assigning here:
if( $username="admin"){ // will assign 'admin' to $username
Should be:
if( $username=="admin"){ // will compare $username == 'admin'
try this sir: (if you have a usertype on your table)
for example:
User_Account:(The table)
User_type(1 is admin)(0 is client)
ID | First_name | Last_name | Username | Password | User_type
1 Michael Jordan MJ23 6rings 1
2 Kobe Bryant KB24 5rings 0
MODEL:
public function login($user,$pass){
$data = array(
'Username' => $user,
'Password' => $pass);
$query = $this->db->get_where('user_account',$data);
return $query->result_array();
}
VIEW:
<form action="<?php echo base_url(); ?>index.php/My_Controller/login_user" method="post">
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<button type="submit">LOGIN</button>
</form>
CONTROLLER:
public function login_user(){
$user = $this->input->post('username');//this is from the name on input
$pass = $this->input->post('password');//this is from the name on input
$result=$this->My_Model->login($user,$pass);
$usertype = $result["0"]["User_type"];//this is from the database, whenever you login a user which is valid this is what you will use to see what is his User_type
if($usertype == 1){
redirect('My_Controller/show_admin');
}
else if($usertype == 0){
redirect('My_Controller/show_client');
}
}
Try this out: if you have questions just comment!
i am new in codeigniter and i am stuck with this if statement. I am selecting from my database the user_status and the user_type of the user and if it is null the value $res cant be empty.
if(empty($res)) {
echo "aaaa";
$this->index();
}
here is my full code in model :
<?php
class Login_model extends MY_Model {
function validate($data) {
$condition = "user_email =" . "'" . $data['useremail'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
$this->db->select('usertype_id,user_status');
$this->db->from('user');
$this->db->where($condition);
$query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result();
}
else {
return NULL;
}
}
}
?>
my controller looks like this :
function validate_credentials() {
$this->load->model('login_model');
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$res['res'] = $this->login_model->validate($data);
if(empty($res)) {
echo "aaaa";
$this->index();
}
My question is, why this $res is always not empty. when i print_r the $res it shows an empty array.
In my project, session is work fine before few days.But now it doesn't work. i can't find the error. plsease help me. it displays error called Severity: Notice
Message: Undefined index: firstname
Filename: user_include/header.php
Line Number: 5
A PHP Error was encountered
Severity: Notice
Message: Undefined
index: id
Filename: user_include/header.php
Line Number: 7
controller
/ Check for user login process
public function user_login_process() {
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
//$this->load->view('admin_page');
$this->home();
}else{
$this->load->view('user_site/login_form');
}
} else {
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('user_site/login_form', $data);
}
}
}
// Logout
public function logout() {
// Removing session data
$sess_array = array(
'email' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('user_site/login_form', $data);
}
}
?>
model
// Read data using username and password
public function login($data) {
$condition = "email =" . "'" . $data['email'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
?>
view
<?php
if (isset($this->session->userdata['logged_in'])) {
$firstname = ($this->session->userdata['logged_in']['firstname']);
$email = ($this->session->userdata['logged_in']['email']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: login");
}
the error is in you user_include/header.php , check the id and firstname are set before you echo them out.
In your model replace following code by given code:
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
To
public function read_user_information($email) {
$this->db->select('firstname, email, id');
$this->db->from('user');
$this->db->where('email',$email);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
In your controller replace following code by given
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
To
$email = $this->input->post('email');
$user_details = $this->login_database->read_user_information($email);
if ($user_details != false) {
// Add user data in session
$this->session->set_userdata('logged_in', $user_details);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
In view, replace your code by following:
<?php
$user_details = $this->session->userdata['logged_in']);
if ($user_details != "") {
$firstname = $user_details['firstname'];
$email = $user_details['email'];
$id = $user_details['id'];
} else {
header("location: login");
}
When I submit my form if password fields are submitted it should update the password else if empty does not update password.
I cannot seem to get the password_hash to update very strange. I can create new users fine with it but not update there password.
All other post are working fine update fine.
Not sure why password not updating? How am I able to fix issue thanks in advance.
<?php
class Model_user extends CI_Model {
public function edit_user($user_id, $data) {
$data = array(
'username' => $data['username'],
'user_group_id' => $data['user_group_id'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'image' => $data['image'],
'status' => $data['status']
);
$this->db->set($data);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user');
if ($data['password']) {
$options = [
'cost' => 11,
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$data = array(
'password' => password_hash($_POST['password'], $options)
);
$this->db->set($data);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user');
}
}
}
Controller
<?php
class Users extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user');
}
public function index() {
$this->get_form();
}
public function update() {
$this->form_validation->set_rules('username', 'Username', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->get_form();
} else {
$this->model_user->edit_user($this->uri->segment(4), $_POST);
redirect('admin/user');
}
}
public function get_form() {
$data['title'] = "Users";
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => 'Home',
'href' => site_url('admin/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => "Users",
'href' => site_url('admin/user')
);
$user_info = $this->model_user->get_user($this->uri->segment(4));
if (isset($_POST['username'])) {
$data['username'] = $_POST['username'];
} elseif (!empty($user_info)) {
$data['username'] = $user_info['username'];
} else {
$data['username'] = '';
}
if (isset($_POST['user_group_id'])) {
$data['user_group_id'] = $_POST['user_group_id'];
} elseif (!empty($user_info)) {
$data['user_group_id'] = $user_info['user_group_id'];
} else {
$data['user_group_id'] = '';
}
$this->load->model('admin/user_group/user_group_model');
$data['user_groups'] = $this->user_group_model->get_user_groups();
if (isset($_POST['password'])) {
$data['password'] = $_POST['password'];
} else {
$data['password'] = '';
}
if (isset($_POST['confirm'])) {
$data['confirm'] = $_POST['confirm'];
} else {
$data['confirm'] = '';
}
if (isset($_POST['firstname'])) {
$data['firstname'] = $_POST['firstname'];
} elseif (!empty($user_info)) {
$data['firstname'] = $user_info['firstname'];
} else {
$data['firstname'] = '';
}
if (isset($_POST['lastname'])) {
$data['lastname'] = $_POST['lastname'];
} elseif (!empty($user_info)) {
$data['lastname'] = $user_info['lastname'];
} else {
$data['lastname'] = '';
}
if (isset($_POST['email'])) {
$data['email'] = $_POST['email'];
} elseif (!empty($user_info)) {
$data['email'] = $user_info['email'];
} else {
$data['email'] = '';
}
if (isset($_POST['image'])) {
$data['image'] = $_POST['image'];
} elseif (!empty($user_info)) {
$data['image'] = $user_info['image'];
} else {
$data['image'] = '';
}
$this->load->model('admin/tool/model_tool_image');
if (isset($_POST['image']) && is_file(FCPATH . 'image/catalog/' . $_POST['image'])) {
$data['thumb'] = $this->model_tool_image->resize($_POST['image'], 100, 100);
} elseif (!empty($user_info) && $user_info['image'] && is_file(FCPATH . 'image/catalog/' . $user_info['image'])) {
$data['thumb'] = $this->model_tool_image->resize($user_info['image'], 100, 100);
} else {
$data['thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
}
$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);
if (isset($_POST['status'])) {
$data['status'] = $_POST['status'];
} elseif (!empty($user_info)) {
$data['status'] = $user_info['status'];
} else {
$data['status'] = 0;
}
$this->load->view('template/user/user_form_view', $data);
}
}
Take a closer look at the edit_user function. You receive $data but you immediately overwrite it. Please note that you don't set a password key to the newly created array. Then you check if ($data['password']) but that will never be true therefore the update will never be done.
There is a problem in your password_hash($_POST['password'], $options).
You passed $_POST['password'] instead of $data['password'].
It took me a while to figure it out I needed to create another variable out side of the if statement in my model like below and then was able to update if new password present.
All working now.
$input_password = $this->input->post('password');
if ($input_password) {
$password = password_hash($input_password, PASSWORD_BCRYPT);
$data_password = array(
'password' => $password
);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user', $data_password);
}
When my user login on in the activity's model. If the user has logged on before it updates that row belonging to the user id. Otherwise should Insert row.
Problem: Currently it just updates the same row as previous. It should insert a new row if user id has not logged on before.
How can I fix problem on model.
<?php
class Model_account_activity extends CI_Model {
public function updateActivity($key, $data) {
$data['user_id'] = $this->session->userdata('user_id');
if (isset($data['user_id'])) {
$user_id = $data['user_id'];
} else {
$user_id = 0;
}
$query = $this->db->query("UPDATE `" . $this->db->dbprefix . "user_activity` SET
`user_id` = '" . (int)$user_id . "',
`key` = " . $this->db->escape($key) . ",
`data` = " . $this->db->escape(serialize($data)) . ",
`date_added` = NOW()
");
if ($query == FALSE) {
$this->addActivity();
return true;
} else {
return false;
}
}
public function addActivity($key, $data) {
$data['user_id'] = $this->session->userdata('user_id');
if (isset($data['user_id'])) {
$user_id = $data['user_id'];
} else {
$user_id = 0;
}
$this->db->query("INSERT INTO `" . $this->db->dbprefix . "user_activity` SET
`user_id` = '" . (int)$user_id . "',
`key` = " . $this->db->escape($key) . ",
`data` = " . $this->db->escape(serialize($data)) . ",
`date_added` = NOW()
");
}
}
Get result from DB by unique ID or primary key then check the query result. If result count is 0 then can insert else update. Example...
$this->db->where('column_name', $user_id); //Unique column or primary_key .It may be $user_id
$query = $this->db->get('table_name');
if($query->num_rows == 0)
{
//Insert query
}
else
{
//Update query
}
Here is how i was able to get it working thanks to #Please Wait all working now.
<?php
class Model_account_activity extends CI_Model {
public function activity($key, $data) {
$user_id = $this->session->userdata('user_id');
$this->db->where('user_id', $user_id);
$query = $this->db->get('user_activity');
$data['user_id'] = $this->session->userdata('user_id');
if (isset($data['user_id'])) {
$user_id = $data['user_id'];
} else {
$user_id = 0;
}
if($query->num_rows() == FALSE) {
$data = array(
'user_id' => $user_id,
'key' => $key,
'data' => serialize($data),
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->insert_id();
$this->db->insert('user_activity', $data);
} else {
$data = array(
'user_id' => $user_id,
'key' => $key,
'data' => serialize($data),
'date_added' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->where('user_id', $user_id);
$this->db->update('user_activity', $data);
}
}
}