Account Edit in CodeIgniter - php

I tried to edit users account but when I loaded the view it does not display the users default account information.Below is my model view and controller. Any help would be greatly appreciated.
I have a database which includes includes all the users information. so I want to retrieve it and perform an update function.
CONTROLLER
/**
* This function is used load user edit information
* #param number $userId : Optional : This is user id
*/
function editOld($userId = NULL)
{
if($userId == null)
{
redirect('pages/settings');
}
$data['userInfo'] = $this->settings_model->getUserInfo($userId);
$data['title'] = 'Settings';
$this->load->view('templates/header');
$this->load->view('pages/settings', $data);
$this->load->view('templates/footer');
}
/**
* This function is used to edit the user information
*/
function editUser()
{
$this->load->library('form_validation');
$userId = $this->session->userdata('user_id');
$this->form_validation->set_rules('name','Full Name','trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|xss_clean|max_length[128]');
$this->form_validation->set_rules('username','Username','trim|required|xss_clean|min_length[3]');
$this->form_validation->set_rules('birthday','Birthday','required|xss_clean');
$this->form_validation->set_rules('gender','Gender','required|xss_clean');
$this->form_validation->set_rules('mobile','Mobile Number','required|min_length[9]|xss_clean');
if($this->form_validation->run() == FALSE)
{
$this->editOld($userId);
}
else
{
$name = $this->input->post('name');
$username = $this->input->post('username');
$email = $this->input->post('email');
$bio = $this->input->post('bio');
$mobile = $this->input->post('mobile');
$birthday = $this->input->post('birthday');
$gender = $this->input->post('gender');
$userInfo = array();
if(empty($password))
{
$userInfo = array('email'=>$email, 'username'=>$username, 'name'=>$name,
'mobile'=>$mobile, 'bio'=>$bio, 'birthday'=>$birthday, 'gender'=>$gender, 'updatedBy'=>$userId, 'updatedDtm'=>date('Y-m-d H:i:s'));
}
else
{
$userInfo = array('email'=>$email, 'username'=>$username, 'name'=>$name,
'mobile'=>$mobile, 'bio'=>$bio, 'birthday'=>$birthday, 'gender'=>$gender, 'updatedBy'=>$userId, 'updatedDtm'=>date('Y-m-d H:i:s'));
}
$result = $this->settings_model->editUser($userInfo, $userId);
if($result == true)
{
$this->session->set_flashdata('success', 'Profile updated successfully');
}
else
{
$this->session->set_flashdata('error', 'Profile update failed');
}
redirect('pages/settings');
}
}
MODEL
function getUserInfo($userId)
{
$this->db->select('id, name, email, username, mobile, birthday, gender, bio');
$this->db->from('users');
$this->db->where('isDeleted', 0);
$this->db->where('id', $userId);
$query = $this->db->get();
return $query->result();
}
/**
* This function is used to update the user information
* #param array $userInfo : This is users updated information
* #param number $userId : This is user id
*/
function editUser($userInfo, $userId)
{
$this->db->where('id', $userId);
$this->db->update('users', $userInfo);
return TRUE;
}
VIEW
<?php
$userId = '';
$name = '';
$email = '';
$mobile = '';
$username = '';
$birthday = '';
$bio = '';
if(!empty($userInfo))
{
foreach ($userInfo as $uf)
{
$userId = $uf->id;
$name = $uf->name;
$email = $uf->email;
$mobile = $uf->mobile;
$username = $uf->username;
$birthday = $uf->birthday;
$bio = $uf->bio;
}
}
?>
<form class="col s12" role="form" action="<?php echo base_url() ?>settings/editUser" method="post" id="editUseri" role="form">
<div class="row">
<div class="input-field col s12">
<input id="name" type="text" class="validate" name="name" value="<?php echo $name; ?>">
<input type="hidden" value="<?php echo $userId; ?>" name="userId" id="userId" />
<label for="name">Full Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="username" type="text" class="validate" data-length="15" name="username" value="<?php echo $username; ?>">
<label for="username">Username</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="email" type="text" class="validate" name="email" value="<?php echo $email; ?>">
<label for="email">Email</label>
</div>
</div>
<div class="box-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
<input type="reset" class="btn btn-default" value="Reset" />
</div>
</form>

You can just pass your details into session and use sessions to display it. remember to update the session .
value="<?php echo $this->session->userdata('username'); ?>"
mark as correct if it works for you.

Try to add :
$this->db->last_query()
to check what is the query going. I think it would needs to set the
$query->result();
$this->db->set() the data part for handling update query

try this only for debug your error
you not checked user session set or not
change from
if($this->form_validation->run() == FALSE)
{
$this->editOld($userId);
}else{
....
....
}
to
if($this->form_validation->run() == FALSE)
{
//your validation error
echo "validation error";
}else if($userId){
//if session set for user
$this->editOld($userId);
}else{
....
....
}

Related

how to alert the message if the bill no is not in a database

how to alert a message if the bill no is not in the database
<form action="<?=site_url('TipUp_Loan/Bill_Delete')?>" class="form-inline" method="POST">
<div class="modal-body">
<div class="form-group">
<label>Bill No: </label>
<input type="text" id="bill" class="form-control" name="Search1" autofocus>
</div>
</div>
<div class="modal-footer text-center">
<button type="submit" id="Delete" onclick="return confirm('Are You sure want to Delete')" class="btn btn-primary" >Delete<i class="icon-bin position-left"></i></button>
</div>
</form>
This is view code....
public function Bill_Delete(){
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$Search = $this->input->post('Search1');
$this->User_model->Bill_Delete($Search);
}
This is a controlller code...
public function Bill_Delete($Search)
{
$this->db->where('billno', $Search);
$this->db->delete('salesitem');
$this->db->where('no', $Search);
$this->db->delete('salesbill');
//echo "Successfully delted";
$this->session->set_flashdata('Add', 'You Deleted The Bill No Successfully');
redirect("Inventory/Bill_Entry","refresh");
}
This is model code...
my problem is how to find that bill no is present in the database, if it not in the database it should alert the message...
You need to use $this->db->affected_rows(); function which return true on bill is deleted else false.
Hope this will help.
//In controller function
public function Bill_Delete(){
$this->form_validation->set_rules('billno','billno','exist[salesitem.billno]');
if ($this->form_validation->run() == FALSE)
{
return $this->set_response( array(), validation_errors(), 'Bill No not exits' );
}
else
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$Search = $this->input->post('Search1');
$this->User_model->Bill_Delete($Search);
}
// In MY_Form_validation library
function exist($str, $value){
list($table, $column) = explode('.', $value, 2);
$query = $this->CI->db->query("SELECT COUNT(*) AS count FROM $table WHERE $column = $str'");
$row = $query->row();
return ($row->count > 0) ? FALSE : TRUE;
}

codeigniter, set_flashdata not working

I read on stack overflow about flash data only valid till next server request, therefore I made new flashdata for couple of message display..
here below is the my code
This is my controller Controller
public function login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|min_length[5]');
if($this->form_validation->run() == TRUE){
$username= $this->input->post('username');
$password= $this->input->post('password');
$this->load->model('Auth_model');
$user = $this->Auth_model->get_login();
if ($user == 0) {
//echo "<script>alert('wrong username');</script>";
$this->session->set_flashdata("msg","Username does not exists");
redirect("auth/login");
}
else{
print_r($user['username']);
if($username == $user['username'] && $password == $user['password']){
$this->session->set_flashdata("success","You are logged in");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user['username'];
redirect("user/dashboard","refresh");
}
else {
//echo "<script>alert('wrong password');</script>";
$this->session->set_flashdata("msg","Password does not match.");
redirect("auth/login");
}
}
}
$this->load->view('login_v');
}
Model
public function get_login(){
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username' => $username));
$query = $this->db->get();
$user = $query->row();
if ($this->db->affected_rows() != 1) {
return false;
}
else {
$data = array(
'user_id' => $user->user_id,
'username' => $user->username,
'password' => $user->password
);
//print_r($data);
//$this->session->set_userdata($data);
return $data;
}
}
view
<?php if(isset($_SESSION['success'])) {?>
<div class="alert alert-success"><?php echo $_SESSION['success']; ?></div>
<?php } ?>
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<?php $this->session->flashdata('msg');?>
<form action="" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" id="username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" id="password">
</div>
<div>
<button class="btn btn-primary" name="login">Login</button>
</div>
</form>
I want to display
$this->session->set_flashdata("msg","Username does not exists");
but my if else is just doing redirect, the commented script tag works fine though.
How to make "msg" work?
Thanks in advance.
please add echo statement in the view like
<?php echo $this->session->flashdata('msg');?>
OR
<?=$this->session->flashdata('msg')?>
It should be like this :
Get your flashdata by using its key, Should be like this
<?php if(!empty($this->session->flashdata('msg'))) {?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata('msg'); ?>
</div>
<?php } ?>
Or simply do like this:
<div class="alert alert-success"><?php echo $this->session->flashdata('msg'); ?></div>
For more : https://www.codeigniter.com/user_guide/libraries/sessions.html

To display invalid email and password error message

In view: login.php
I am using this view file in two places one for user login and other displaying the invalid user and password message. Below i mentioned some code but it does not work. give me any suggestion regarding this problem.
<div class="login-content">
/*
message to be displayed here:
i try this one:<?php if(!(authentication($email,$password) == TRUE)){
echo "Invalid email address or password";
}?>
*/
<form action="<?php echo site_url('auth/check');?>" method="POST" class="margin-bottom-0" data-parsley-validate="true" onsubmit = "return Validate();" >
<div class="form-group m-b-15">
<input type="text" name="txtemail" id="txtemail" class="form-control input-lg" placeholder="<?php echo $language['Email'];?>" data-parsley-required='true' maxlength="95"/>
</div>
<div class="form-group m-b-15">
<input type="password" name="txtpassword" id="txtpassword" class="form-control input-lg" placeholder="<?php echo $language['Password'];?>" data-parsley-required='true' maxlength="95"/>
</div>
In Controller: Auth.php
This is a function for checking the user validation. I want to display a message using this function in else condition.
public function check(){
$email = $this->input->post('txtemail');
$password = $this->encrypt($this->input->post('txtpassword'));
$this->load->model('cmsuser_model');
$user = $this->cmsuser_model->authentication($email,$password);
if(!is_null($user))
{
$this->session->set_userdata('user', $user);
$this->session->set_userdata('profile_image',$user->image);
$this->session->set_userdata('is_manager','0');
$this->load->model('association_model');
$table = '';
$limit = '';
$order_by = '';
$group_by = '';
$start = '';
$fields = '';
$where = array();
$where['created_by'] = $this->session->userdata['user']->cmsuid;
$dt = $this->association_model->get_all($fields, $where, $table, $limit, $order_by, $group_by, $start);
$this->session->set_userdata('ass_id', $dt[0]['ass_id']);
redirect(base_url('index.php/welcome'), 'refresh');
}
else{
//Browser redirect to this else condition but i am not able to display message in `view(login.php)` file.
redirect(base_url('index.php/auth/login'), 'refresh');
}
exit;
}
public function check(){
$email = $this->input->post('txtemail');
$password = $this->encrypt($this->input->post('txtpassword'));
$this->load->model('cmsuser_model');
$user = $this->cmsuser_model->authentication($email,$password);
if(!is_null($user))
{
$this->session->set_userdata('user', $user);
$this->session->set_userdata('profile_image',$user->image);
$this->session->set_userdata('is_manager','0');
$this->load->model('association_model');
$table = '';
$limit = '';
$order_by = '';
$group_by = '';
$start = '';
$fields = '';
$where = array();
$where['created_by'] = $this->session->userdata['user']->cmsuid;
$dt = $this->association_model->get_all($fields, $where, $table, $limit, $order_by, $group_by, $start);
$this->session->set_userdata('ass_id', $dt[0]['ass_id']);
redirect(base_url('index.php/welcome'), 'refresh');
}
else{
$url=echo base_url('login.php').'?status=err';
redirect($url, 'refresh');
//this will redirect you to the login page with the parameter status in the url
}
exit;
}
in login.php View File
<?php
$satatus = $_GET['status'];
if($status == 'err'){
?>
//add this div right above the login section
<div>Wrong Username/Password !!</div>
<div class="login-content">
/*
message to be displayed here:
i try this one:<?php if(!(authentication($email,$password) == TRUE)){
echo "Invalid email address or password";
}?>
*/
<form action="<?php echo site_url('auth/check');?>" method="POST" class="margin-bottom-0" data-parsley-validate="true" onsubmit = "return Validate();" >
<div class="form-group m-b-15">
<input type="text" name="txtemail" id="txtemail" class="form-control input-lg" placeholder="<?php echo $language['Email'];?>" data-parsley-required='true' maxlength="95"/>
</div>
<div class="form-group m-b-15">
<input type="password" name="txtpassword" id="txtpassword" class="form-control input-lg" placeholder="<?php echo $language['Password'];?>" data-parsley-required='true' maxlength="95"/>
</div>
<?php
}
?>

How to get login username and insert into another table in codeigniter php

Hi i am a blog page where i will be inserting blogs from admin panel.while inserting blogs into database i need to insert admin username as well into the database for the blogs.How to get the admin username and insert into blogs table.
Controller:
function addblogs()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('blog_title','Blog Title');
$this->form_validation->set_rules('description','Blog Description');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='blogs';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
else
{
$this -> blogs_model -> insertblogs();
$this->flash->success('<h2>blogs Added Successfully!</h2>');
redirect('blogs');
}
}
Model:
function insertblogs()
{
$username = $_SESSION['name'];
$title=$this->input->post('blog_title');
$result = str_replace(" ", "-", $title);
$data=array(
'blog_title'=>$this->input->post('blog_title'),
'blogtitle'=>$result,
'description'=>$this->input->post('description'),
'user'=>$username
);
$this->db->insert('blogs',$data);
}
}
View:
<?php
$form_attributes = array('name'=>'adds', 'id'=>'adds', 'enctype' => "multipart/form-data");
echo form_open('blogs/addblogs',$form_attributes);
?>
<div class="element">
<label for="blogtitle"><font color ="black">Blog Title</font></label>
<input class="text err" type="text" name="blog_title" id="blog_title" value="<?php echo set_value('blog_title');?>"/>
</div>
<div class="element">
<label for="description"><font color ="black">Blog Description</font></label>
<textarea name="description" id="myArea1" rows="4" cols="173"></textarea>
</div> <br/>
<div align="center">
<input type="submit" id="submit" value="Submit" />
</div>
<div class="clear"></div>
<?php echo form_close();?>
Login Controller:
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['records']=$this->career_model->get_jobs_list();
$data['mode'] = "all";
$data['mainpage'] = "career";
$this->load->view('templates/template', $data);
}
else{
$this->load->view('login');
}
Login Model:
<?php
class login_model extends MY_Model
{
function login_user($user_name = '', $password=''){
$userdetails = array(
'user_name' => $user_name,
'password' => md5($password),
);
$this->db->where($userdetails);
$query = $this->db->get('login_details');
if($query->num_rows()):
$user = $query->result();
$sess_arry = array(
'user_id' => $user[0]->user_id,
'name' => $user[0]->name
);
$this->session->set_userdata('admin_logged_in', $sess_arry); //add admin details to session
return true;
else:
return false;
endif;
}
}
You can some change your model in insertblogs() method like that :
$this->load->library('session');
$logged_data = $this->session->userdata('admin_logged_in');
$user_id = $logged_data['user_id'];
$user_name = $logged_data['name'];
$username = $user_name;//$_SESSION['name'];
You can get the name of the logged-in user by:
$username = $this->session->userdata('username');
now you can use this $username to insert it in database or you can perform some other functionality.

how update value input form class result

I Have a profile page and admin can edit profile users,
all process on one page done,How i can refresh and update value form data after success query update ?
User.class file :
class User {
...
public function updateUser($id, $firstname, $lastname, $phone, $birthday, $managerid)
{
$con = $this->DBconnect();
$id = (int)$id;
$managerid = $this->checkParam($managerid);
$firstname = $firstname;
$lastname = $lastname;;
$mobile = $phone;
$birthday = $this->checkParam($birthday);
$query = "UPDATE `users` SET `manager_id` = :manager_id,`firstname` = :firstname,`lastname` = :lastname,`birthday` = :birthday,`mobile` = :mobile WHERE `id` = :id";
$result = $con->prepare($query);
$result->BindParam(':id', $id, PDO::PARAM_INT);
$result->BindParam(':manager_id', $managerid, PDO::PARAM_INT);
$result->BindParam(':firstname', $firstname);
$result->BindParam(':lastname', $lastname);
$result->BindParam(':birthday', $birthday);
$result->BindParam(':mobile', $mobile);
$check = $result->execute();
return true;
}}
profile.php file :
<?php
if (isset($_GET['id'])) {
$id = (int)$_GET['id'];
}
$user = new User();
$user_info = $user->getuser($id);
while ($info = $user_info->fetch(PDO::FETCH_ASSOC)) {
$firstname = $info['firstname'];
$lastname = $info['lastname'];
$mobile = $info['mobile'];
$birthday = $info['birthday'];
$managerid = $info['manager_id'];
}
$manager_ob = new Manager();
$managers = $manager_ob->getAllManager();
$managers_name = array();
while ($manager = $managers->fetch(PDO::FETCH_ASSOC)) {
$managers_list[] = $manager;
}
if (isset($_POST['edit-profile'])) {
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
}
?>
<form method="post" action="#" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label">ID</label>
<div class="col-sm-10"><input type="text" readonly class="form-control" name="user_id" id="user_id" value="<?php echo check_param($id); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_firstname" value="<?php echo check_param($firstname); ?>" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_lastname" value="<?php echo check_param($lastname); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_mobile" value="<?php echo check_param($mobile); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label" for="birthday">Birthday
</label>
<div class="col-sm-10"><input id="birthday" type="text" class="form-control" name="user_birthday"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Manager</label>
<div class="col-sm-10"><select class="form-control m-b" name="manager_id">
<?php foreach ($managers_list as $managers_n) { ?>
<option <?php if ($managers_n['id'] == $managerid) {
echo 'selected';
} ?>
value="<?php echo $managers_n['id']; ?>"> <?php echo $managers_n['name']; ?></option>;
<?php }
?>
</select>
</div>
</div>
<input type="submit" name="edit-profile" class="btn btn-block btn-w-m btn-success"
value="Edit profile">
</form>
i load profile data after submit edit :
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
only display message Profile Edited but must be refresh page for renew data
I must fetch again query for update values? or have better way ?
I suggest you use Ajax for this this is probably the best way to change the data without refreshing. More info about (jQuery) ajax http://api.jquery.com/jquery.ajax/
Your other option is to force a refresh after the submit. You can do this in PHP like so:
Header('Location: '.$_SERVER['PHP_SELF']);
I would suggest choosing ajax to tackle this problem though.
Good luck :)

Categories