I am trying to set my own callback message for codeigniter. But when I try to make my own it will show both messages codeigniter one and my custom one. Here is a link to my errors are showing up the top error is one that I would like to use http://postimg.org/image/v9ilejmnt/
How am I able to make it only show my custom error message?
I also use hmvc so I have had to add run($this) in the form validation to make callback work.
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('user');
$this->load->library('form_validation');
$this->lang->load('common/login', 'english');
if($this->session->userdata('user_id')) {
redirect('dashboard');
} else {
return false;
redirect('login');
}
}
public function index() {
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[12]|xss_clean|callback_validate');
$this->form_validation->set_rules('password', 'Password', 'required|xss_clean');
if($this->form_validation->run($this) == false) {
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('login');
$this->load->view('common/login', $data);
} else {
redirect('dashboard');
}
}
function validate() {
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->user->login($username, $password)) {
return true;
} else {
$this->error['warning'] = $this->lang->line('error_login');
return !$this->error;
}
}
}
View
<?php echo modules::run('common/header/index');?>
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-3 col-md-4 col-md-offset-4 col-sm-offset-4 col-sm-4">
<div class="panel panel-default">
<div class="panel-heading"><h2 class="panel-title">Administration Login</h2></div>
<div class="panel-body">
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
<form action="<?php echo $action;?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="input-group"><span class="input-group-addon"><i class="fa fa-user"></i> </span>
<input type="text" name="username" value="" placeholder="Username" class="form-control" size="50" />
</div>
<?php echo form_error('username', '<div class="text-danger">', '</div>'); ?>
</div>
<div class="form-group">
<div class="input-group"><span class="input-group-addon"><i class="fa fa-lock"></i></span>
<input type="password" name="password" value="" placeholder="Password" class="form-control"/>
</div>
<?php echo form_error('password', '<div class="text-danger">', '</div>'); ?>
</div>
<div class="form-group">
<div class="text-right">
<button type="submit" class="btn btn-primary"><i class="fa fa-key"></i> Login</button>
</div>
</div>
</form>
</div><!--/. Panel Body -->
</div><!--/. Panel Panel Default -->
</div>
</div>
</div>
<?php echo modules::run('common/footer/index');?>
you forgot to set error message for your your callback.
$this->form_validation->set_message('validate', 'invalid username or password');
return FALSE;
or you can do
$this->form_validation->set_message('validate', $this->lang->line('error_login'));
return FALSE;
in your view file you are showing errors for each fields (CI form validation messages) as well as your own <?php echo $error_warning; ?>
you should use following code
function validate() {
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->user->login($username, $password)) {
return true;
} else {
$this->form_validation->set_message('validate', $this->lang->line('error_login'));
return FALSE;
}
and remove this block from view
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
}
and remove this too
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
I worked it out today. When want to use both validation methods custom and form validation can not use callbacks.
public function index() {
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|xss_clean');
if($this->form_validation->run($this) == false) {
$data['title'] = $this->lang->line('heading_title');
$data['text_heading'] = $this->lang->line('text_heading');
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('login');
$this->load->view('common/login', $data);
} else {
if($this->validate()) {
redirect('dashboard');
} else {
$data['title'] = $this->lang->line('heading_title');
$data['text_heading'] = $this->lang->line('text_heading');
if (array_key_exists('warning', $this->error)) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('login');
$this->load->view('common/login', $data);
}
}
}
Related
I am working on Code Igniter and stuck in a place where I need to change the password of a signed-in user. I need help in picking up the user id of the signed-in user and through it I want to update the password of that user.
The following are the images of controller and models created of the project respectively.
Create html link:
<i class="fa fa-circle-o"></i>Change password
Create user controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
// Load session library
$this->load->library('session');
$this->load->model('Data_model');
}
public function changePassword()
{
$web = array();
$web['title'] = 'Change password';
$web['content'] = 'web/password';
$this->form_validation->set_rules('old_password', 'Old password', 'required|callback_check_password');
$this->form_validation->set_rules('new_password', 'New password', 'required');
$this->form_validation->set_rules('confirm_password', 'Confirm password', 'required|matches[new_password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('web_template',$web);
} else {
$id = $this->user_id;
$data = array(
'user_password' => $this->input->post('new_password'),
);
$this->Common_model->Data_model('user_login', $data, 'id', $id);
$this->session->set_flashdata('msg', 'Password changed Successfully');
redirect('user/changePassword');
}
}
function check_password($password) {
if($this->user_id)
$id = $this->user_id;
else
$id = '';
$result = $this->Data_model->check_user_password($id, $password);
if($result > 0)
$response = true;
else {
$this->form_validation->set_message('check_password', 'Old password is wrong');
$response = false;
}
return $response;
}
}
Change password html page in view:
<section class="content">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title"><?php echo $title; ?></h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fa fa-minus"></i></button>
</div>
</div>
<?php
$attributes = array('class' => 'form-horizontal', 'id' => 'changePassword');
echo form_open('user/changePassword', $attributes);
?>
<div class="box-body">
<?php if (!empty($this->session->flashdata('msg'))) : ?>
<div class="alert alert-success alert-dismissable alertDiv"> <?php echo $this->session->flashdata('msg'); ?> </div>
<?php endif; ?>
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Old password</label>
<div class="col-md-8">
<input type="password" name="old_password" value="<?php echo (isset($form_data) ? $form_data->old_password : set_value('old_password')); ?>" class="form-control" id="old_password" placeholder="Old password">
<?php echo form_error('old_password', '<div class="error">', '</div>'); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">New password</label>
<div class="col-md-8">
<input type="password" name="new_password" value="<?php echo (isset($form_data) ? $form_data->new_password : set_value('new_password')); ?>" class="form-control" id="new_password" placeholder="New password" autocomplete="off">
<?php echo form_error('new_password', '<div class="error">', '</div>'); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Confirm Password</label>
<div class="col-md-8">
<input type="password" name="confirm_password" value="<?php echo (isset($form_data) ? $form_data->confirm_password : set_value('confirm_password')); ?>" class="form-control" id="confirm_password" placeholder="Confirm Password" autocomplete="off">
<?php echo form_error('confirm_password', '<div class="error">', '</div>'); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-5" style="margin-top: 10px;">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
<?php form_close(); ?>
</div>
<!-- /.box -->
</section>
Create Data_model in model add this function:
// Update data to table
public function update($table, $data, $primaryfield, $id)
{
$this->db->where($primaryfield, $id);
$q = $this->db->update($table, $data);
return $q;
}
//Check the old password:
function check_user_password($id = '', $password) {
$this->db->where('user_password', $password);
$this->db->where('id', $id);
return $this->db->get('user_login')->num_rows();
}
I am learning to develop with codeigniter 3.1.8, for that I am confronted with a problem: I am confronted with a problem: I am redirected in a blank page and my errors do not display. please I would like to give you a hand
here is the function of the model for insertion
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_root extends CI_Model{
function isertion_root(){
$root=array(
'nom_admin'=>'$user_name',
'prenom_admin'=>'$user_prenom',
'email_admin'=>'$user_email',
'date_nais_admin'=>'$date_nais',
'date_inscription_admin'=>'NOW(),false',
'avatar_root'=>'$avatar_root',
'password_root'=>'$pssword_root'
);
$this->db->insert('root', $root);
}
/**
* #param $email
* #param $password
* #return bool
*/
function login_root($email,$password){
$this->db->select('*');
$this->db->from('root');
$this->db->where('email_admin',$email);
$this->db->where('password_root',$password);
if ($query=$this->db->get())
{
return $query->row_array();
}
else{
return false;
}
}
public function email_check($email_admin){
$this->db->select('*');
$this->db->from('root');
$this->db->where('email_admin',$email_admin);
$query=$this->db->get();
if($query->num_rows()>0){
return false;
}else{
return true;
}
}
}
here is the function of the controller for insertion
class Root extends CI_Controller{
function __construct(){
parent:: __construct();
$this->load->database();
$this->load->model('M_root');
$this->load->library('upload');
$this->load->library('form_validation');
$this->load->helper(array('form', 'url'));
$this->load->library('session');
}
public function index()
{
$this->load->view("register.php");
}
//debut fonction d'enregistrement
public function isertion_root(){
if($this->input->post('registersubmit')){
$config['upload_path'] = './assets/avatar-root/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->upload->initialize($config);
if(!empty($_FILES['filefoto']['name']))
{
if ($this->upload->do_upload('filefoto'))
{
$gbr = $this->upload->data();
//Compress Image
$config['image_library']='gd2';
$config['source_image']='./assets/avatar-root/'.$gbr['file_name'];
$config['create_thumb']= FALSE;
$config['maintain_ratio']= FALSE;
$config['quality']= '60%';
$config['new_image']= './assets/avatar-root/'.$gbr['file_name'];
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$this->form_validation->set_rules('nom_admin', 'nom administrateur', 'trim|required|min_length[3]|max_length[23]|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('prenom_admin', 'prenom administrateur', 'trim|required|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('email_admin', 'Email administrateur', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('date_nais_admin', 'Date de naissance administateur', 'trim|required');
$this->form_validation->set_rules('avatar_root', 'Avatar root', 'trim|required');
$this->form_validation->set_rules('password_root', 'password root', 'trim|required|min_length[8]|xss_clean');
$this->form_validation->set_rules('conf_password', 'confirm password', 'trim|required|matches[password]');
$root = array(
'nom_admin' => strip_tags($this->input->post('nom_admin')),
'prenom_admin' => strip_tags($this->input->post('prenom_admin')),
'email_admin' => strip_tags($this->input->post('email_admin')),
'date_nais_admin' => strip_tags($this->input->post('date_nais_admin')),
'avatar_root' => strip_tags($this->input->post('avatar_root')),
'password_root' => password_hash($this->input->post('password'),PASSWORD_DEFAULT)
);
print_r($root);
if ($this->form_validation->run() == TRUE)
{
$email_check=$this->M_root->email_check($root['email_admin']);
if($email_check){
$this->M_root->isertion_root($root);
$this->session->set_flashdata('success_msg', 'Registered successfully.Now login to your account.');
redirect('root/login_view');
}
}
else{
$this->load->view('register');
}
}
}
}
}
//fin fonction d'enregistrement
view
<span style="background-color:red;">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Creation d'un compte</h3>
</div>
<div class="panel-body">
<p class="alert-danger"><?php
$error_msg=$this->session->flashdata('error_msg');
if($error_msg){
echo $error_msg;
}
?></p>
<?php echo validation_errors(); ?>
<form role="form" method="post" enctype="multipart/form-data" autocomplete="off" action="<?php echo base_url().'Root/isertion_root'?>">
<fieldset>
<div class="form-group">
<?php echo form_error('nom_admin'); ?>
<input class="form-control" placeholder="Votre nom" name="nom_admin" value="<?php echo set_value('nom_admin'); ?>"type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Votre prenom" name="prenom_admin" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email_admin" type="email" autofocus>
</div>
<div class="form-group">
<div class="form-group">
<input class="form-control" placeholder="votre date de naissance" name="date_nais_admin" type="date" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="mot de passe " name="password_root" type="password" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="confirmez votre mot de passe" name="conf_password" type="password" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="votre photo" name="avatar_root" type="file" value="">
</div>
<input class="btn btn-lg btn-success btn-block" type="submit" value="Register" name="registersubmit" >
</fieldset>
</form>
<center><b>Already registered ?</b> <br></b>Login here</center><!--for centered text-->
</div>
</div>
</div>
</div>
</div>
</span>
Once i faced with this same problem i rectified by using this please try this.
ini_set('display_errors', 1);
Your original code contained many ifs and no elses. This mean if an if condition evaluates to false there is no reason for anything to be displayed.
This is a better way of doing it. If you keep everything all in one function and avoid redirects you can properly repopulate the input fields when an error occurs either from form validation or image uploading.
public function index() {
if ($this->input->post('registersubmit')) {
$this->form_validation->set_rules('nom_admin', 'nom administrateur', 'trim|required|min_length[3]|max_length[23]|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('prenom_admin', 'prenom administrateur', 'trim|required|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('email_admin', 'Email administrateur', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('date_nais_admin', 'Date de naissance administateur', 'trim|required');
$this->form_validation->set_rules('avatar_root', 'Avatar root', 'trim|required');
$this->form_validation->set_rules('password_root', 'password root', 'trim|required|min_length[8]|xss_clean');
$this->form_validation->set_rules('conf_password', 'confirm password', 'trim|required|matches[password]');
if ($this->form_validation->run()) {
$this->load->library('upload');
$config['upload_path'] = './assets/avatar-root/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->upload->initialize($config);
if ($this->upload->do_upload('filefoto')) {
$gbr = $this->upload->data();
//Compress Image
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/avatar-root/' . $gbr['file_name'];
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['quality'] = '60%';
$config['new_image'] = './assets/avatar-root/' . $gbr['file_name'];
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$root = array(
'nom_admin' => strip_tags($this->input->post('nom_admin')),
'prenom_admin' => strip_tags($this->input->post('prenom_admin')),
'email_admin' => strip_tags($this->input->post('email_admin')),
'date_nais_admin' => strip_tags($this->input->post('date_nais_admin')),
'avatar_root' => strip_tags($this->input->post('avatar_root')),
'password_root' => password_hash($this->input->post('password'), PASSWORD_DEFAULT)
);
// i have a feeling you are checking if an email already exists here
// you can use form validations is_unique function in the rules above and forgo this
if ($this->M_root->email_check($root['email_admin'])) {
$this->M_root->isertion_root($root);
$this->session->set_flashdata('success_msg', 'Registered successfully.Now login to your account.');
redirect('root/login_view');
} else {
$this->session->set_flashdata('error_msg', 'bad email');
}
} else {
$this->session->set_flashdata('error_msg', $this->upload->display_errors());
}
}
}
$this->load->view("register.php");
}
You just have to change your form action to be blank so it submits to the same page.
Also in each input value except passwords you should do something like this:
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
This way the user won't lose their input when natural errors occur due to them entering wrong information or whatever.
I am unable to login with email address. login is done through username only, when i try to login with email it redirect me to login page.
Please help me, so i can login with email also.
I checked many online sources but not helpful for me.
My Controllers:
STORE_ACCOUNTS_CONTROLLER
function get_with_double_condition($col1, $value1, $col2, $value2)
{
$this->load->model('mdl_store_accounts');
$query = $this->mdl_store_accounts->get_with_double_condition($col1, $value1, $col2, $value2);
return $query;
}
YOURACCOUNTS_CONTROLLER
function submit_login()
{
$this->load->module('site_security');
$this->load->module('store_accounts');
$submit = $this->input->post('submit',TRUE);
if ($submit=="Submit") {
//process the form
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username','required|min_length[5]|max_length[60]|callback_username_check');
$this->form_validation->set_rules('pword','Password','required|min_length[7]|max_length[35]');
if ($this->form_validation->run()==TRUE) {
//figure out user_id
$col1 = 'username';
$value1 = $this->input->post('username', TRUE);
$col2 = 'email';
$value2 = $this->input->post('email', TRUE);
$query = $this->store_accounts->get_with_double_condition($col1, $value1, $col2, $value2);
foreach ($query->result() as $row) {
$user_id = $row->id;
}
//send them to the private page
$this->_in_you_go($user_id, $login_type);
$remember = $this->input->post('remember', TRUE);
if ($remember=="remember-me") {
$login_type = "longterm";
}
else
{
$login_type = "shortterm";
}
}
else
{
echo validation_errors();
}
}
}
function username_check($str)
{
$this->load->module('site_security');
$this->load->module('store_accounts');
$error_msg = "You did not enter a correct username and/or password.";
$col1 = 'username';
$value1 = $str;
$col2 = 'email';
$value2 = $str;
$query = $this->store_accounts->get_with_double_condition($col1, $value1, $col2, $value2);
$num_rows = $query->num_rows();
if ($num_rows<1) {
$this->form_validation->set_message('username_check', $error_msg);
return FALSE;
}
foreach ($query->result() as $row) {
$pword_on_table = $row->pword;
}
$pword = $this->input->post('pword', TRUE);
$result = $this->site_security->_verify_hash($pword, $pword_on_table);
if ($result==TRUE) {
return TRUE;
}
else
{
$this->form_validation->set_message('username_check', $error_msg);
return FALSE;
}
}
My Model:
STORE_ACCOUNTS_MODEL
function get_with_double_condition($col1, $value1, $col2, $value2)
{
$table = $this->get_table();
$this->db->where($col1, $value1);
$this->db->or_where($col2, $value2);
$query=$this->db->get($table);
return $query;
}
My View:
LOGIN_PAGE
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form class="form-signin" action="<?= $form_location ?>" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputText" class="sr-only">Username or Email address</label>
<input type="text" name="username" value="<?= $username?>" id="inputEmail" class="form-control" placeholder="Username or Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="pword" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" name="remember" value="remember-me"> Remember me
</label>
</div>
<button name="submit" value="Submit" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
</div>
</div> <!-- /container -->
Your form is only POST username.
In case of email this don't validate in code
$this->form_validation->set_rules('username','Username','required|min_length[5]|max_length[60]|callback_username_check');
and $value2 will be empty
$value2 = $this->input->post('email', TRUE);
I didnt read the whole code ill provide you with a simple code that will be effective :
View File:
<form action='controller.php' method='POST'>
<input type='email' name='email'>
<input type='password' name='pass'>
<input type='submit' value='login' name='login'>
</form>
Controller.php
(define the model in constructor first in order to execute the statement $this->login_model->login();)
if(isset($_POST['login'])){
$condition=$this->login_model->login();
if(!empty($condition) && isset($condition)){
redirect('');//redirect to where ever you want or you can set the session as well
}}
login_model.php
public function login(){
$email=$_POST['email'];
$password=$_POST['pass'];
$this->db->select('*');
$this->db->from('table_name');
$this->db->where('email',$email);
$this->db->where('pass',$password);
$q= $this->db->get()-results();
return $q;
}
I have to do a codeigniter crud operation. But now i want to add pagination search and sort for that.I used lots of tutorials to do that. But i can't understand. To anyone who knows please help me to do that. Thank you.
controller
class User_controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user_model');
$this->load->library('form_validation');
}
// load user_list view
public function index()
{
$this->load->view('admin_include/header');
$this->load->view('admin_pages/user_list');
}
// show all the users in view
public function fillgrid(){
$this->user_model->fillgrid();
}
function fetch_record(){
$this->user_model->fetch_record();
}
// validate and insert new user data
public function create(){
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
echo'<div class="alert alert-danger">'.validation_errors().'</div>';
exit;
}
else{
$this->user_model->create();
}
}
// edit user
public function edit(){
$id = $this->uri->segment(3);
$this->db->where('id',$id);
$data['query'] = $this->db->get('user');
$data['id'] = $id;
$this->load->view('admin_pages/user_edit', $data);
}
// update validation
public function update(){
$res['error']="";
$res['success']="";
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else{
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'));
$this->db->where('id', $this->input->post('hidden'));
$this->db->update('user', $data);
$res['success'] = '<div class="alert alert-success">One record updated Successfully</div>';
}
header('Content-Type: application/json');
echo json_encode($res);
exit;
}
//delete user
public function delete(){
$id = $this->input->POST('id');
$this->db->where('id', $id);
$this->db->delete('user');
echo'<div class="alert alert-success">One record deleted Successfully</div>';
exit;
}
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function fillgrid(){
$this->db->order_by("id", "desc");
$data = $this->db->get('user');
foreach ($data->result() as $row){
$edit = base_url().'index.php/user_controller/edit/';
$delete = base_url().'index.php/user_controller/delete/';
echo "<tr>
<td>$row->firstname</td>
<td>$row->lastname</td>
<td>$row->email</td>
<td>$row->contact_no</td>
<td>$row->address</td>
<td>$row->created</td>
<td><a href='$edit' data-id='$row->id' class='btnedit' title='edit'><i class='glyphicon glyphicon-pencil' title='edit'></i></a> <a href='$delete' data-id='$row->id' class='btndelete' title='delete'><i class='glyphicon glyphicon-remove'></i></a></td>
</tr>";
}
exit;
}
public function create(){
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'),
'created'=>date('d/m/y'));
$this->db->insert('user', $data);
echo'<div class="alert alert-success">One record inserted Successfully</div>';
exit;
}
private function edit(){}
private function delete(){}
//2015.7.26
//set table name to be used by all functions
var $table = 'user';
function fetch_record($limit, $start)
{
$this->db->limit($limit, $start);
$query = $this->db->get($this->user);
return ($query->num_rows() > 0) ? $query->result() : FALSE;
}
function record_count()
{
return $this->db->count_all_results('user');
}
//2015.7.26
}
//2015.7.26
public function pagination(){
$page_number = $this->input->post('page_number');
$item_par_page = 2;
$position = ($page_number*$item_par_page);
$result_set = $this->db->query("SELECT * FROM user LIMIT ".$position.",".$item_par_page);
$total_set = $result_set->num_rows();
$page = $this->db->get('user') ;
$total = $page->num_rows();
//break total recoed into pages
$total = ceil($total/$item_par_page);
if($total_set>0){
$entries = null;
// get data and store in a json array
foreach($result_set->result() as $row){
$entries[] = $row;
}
$data = array(
'TotalRows' => $total,
'Rows' => $entries
);
$this->output->set_content_type('application/json');
echo json_encode(array($data));
}
exit;
}
view
<div class="well">
<form class="form-inline" role="form" id="frmadd" action="<?php echo base_url() ?>index.php/user_controller/create" method="POST">
<!--First Name-->
<div class="form-group">
<label class="sr-only" for="firstname">First Name</label>
<input type="text" name="firstname" class="form-control" id="firstname" placeholder="First name">
</div>
<!--/First Name-->
<!--Last Name-->
<div class="form-group">
<label class="sr-only" for="lastname">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lastname" placeholder="Last Name">
</div>
<!--/Last Name-->
<!-- email-->
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">#</div>
<input class="form-control" name="email" type="email" placeholder="Enter email">
</div>
</div>
<!-- email-->
<!--Contact-->
<div class="form-group">
<label class="sr-only" for="contact_no">Contact</label>
<input type="text" class="form-control" name="contact_no" id="contact_no" placeholder="contact number">
</div>
<!--/Contact-->
<!--Address-->
<div class="form-group">
<label class="sr-only" for="address">Address</label>
<input type="text" name="address" class="form-control" id="exampleInputPassword2" placeholder="Address">
</div>
<!--/Address-->
<!--submit-->
<input type="submit" class="btn btn-success" id="exampleInputPassword2" value="submit">
<!--/submit-->
</div>
</form>
</div>
<table class="table">
<thead><tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Contact</th><th>Address</th><th>created</th><th>Action</th></tr></thead>
<tbody id="fillgrid">
</tbody>
<tfoot></tfoot>
</table>
<!-- //2015.7.26-->
<div class="row clear-fix">
<div class="col-md-4 pull-right">
<button id="previous" class="btn btn-sm btn-primary">Previous</button>
<lable>Page <lable id="page_number" name="page_number" ></lable> of <lable id="total_page" name="total_page"></lable></lable>
<button id="next" class="btn btn-sm btn-primary">Next</button>
</div>
</div>
<div style="text-align: center">
<!--//2015.7.26-->
</div>
</div>
</div>
<script>
$(document).ready(function (){
//fill data
var btnedit='';
var btndelete = '';
fillgrid();
// add data
$("#frmadd").submit(function (e){
e.preventDefault();
$("#loader").show();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
type:'POST',
data:data
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
});
function fillgrid(){
$("#loader").show();
$.ajax({
url:'<?php echo base_url() ?>index.php/user_controller/fillgrid',
type:'GET'
}).done(function (data){
$("#fillgrid").html(data);
$("#loader").hide();
btnedit = $("#fillgrid .btnedit");
btndelete = $("#fillgrid .btndelete");
var deleteurl = btndelete.attr('href');
var editurl = btnedit.attr('href');
//delete record
btndelete.on('click', function (e){
e.preventDefault();
var deleteid = $(this).data('id');
if(confirm("are you sure")){
$("#loader").show();
$.ajax({
url:deleteurl,
type:'POST' ,
data:'id='+deleteid
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
}
});
//edit record
btnedit.on('click', function (e){
e.preventDefault();
var editid = $(this).data('id');
$.colorbox({
href:"<?php echo base_url()?>index.php/user_controller/edit/"+editid,
top:50,
width:500,
onClosed:function() {fillgrid();}
});
});
});
}
});
</script>
i think you have to check your db field name it will work definitely you are missing some db field name...
I have a full working code with retrieve insert update and delete data to database.
All is working well, but if I delete some data, it is deleted but when direct to my view page again, then it will return "Invalid argument supplied for foreach()".
When I press again my view page link it is all normal and the data I delete is gone too, this is just happen with delete function.
Code :
Controller :
public function merk(){
//$data["result"] = $this->modelAdminMerk->getMerk();
$data["totalRows"] = $this->modelAdminMerk->getTotalRows();
$config["base_url"] = base_url() . "admin/merk";
$config["per_page"] = 15;
$config["total_rows"] = $data["totalRows"];
$config["uri_segment"] = 3;
$config["num_links"] = 10;
$this->pagination->initialize($config);
if( ! $this->uri->segment(3)){
$page = 0;
}else{
$page = $this->uri->segment(3);
}
$data["results"] = $this->modelAdminMerk->getMerkByPages($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view("adminView/adminHeader");
$this->load->view("adminView/adminMerk", $data);
$this->load->view("adminView/adminFooter");
}
public function insertMerk(){
$this->load->view("adminView/adminHeader");
$this->load->view("adminView/adminInsertMerk");
$this->load->view("adminView/adminFooter");
}
public function validateInsertMerk(){
$this->form_validation->set_rules("namaMerk", "Nama Merk", "trim|required|min_length[3]|max_length[30]");
if($this->form_validation->run()){
$newMerk = array("merk" => $this->input->post("namaMerk"));
$this->modelAdminMerk->insertMerk($newMerk);
$this->merk();
}else{
echo "GAGAL!!!";
}
}
public function editMerk($id){
$data["merk"] = $this->modelAdminMerk->getMerkById($id);
$this->load->view("adminView/adminHeader");
$this->load->view("adminView/adminEditMerk", $data);
$this->load->view("adminView/adminFooter");
}
function validateEditMerk(){
$this->form_validation->set_rules("namaMerk", "Nama Merk", "trim|required|min_length[3]|max_length[30]");
if($this->form_validation->run()){
$newMerk = array("merk" => $this->input->post("namaMerk"));
$this->modelAdminMerk->editMerk($this->input->post("id"), $newMerk);
$this->merk();
}else{
echo "GAGAL";
}
}
public function deleteMerk($id){
$this->modelAdminMerk->deleteMerk($id);
$this->merk();
}
Model :
function getMerk(){
$data = $this->db->query("SELECT * FROM merkbarang");
return $data->result();
}
function getMerkById($id){
$this->db->where("id", $id);
$data = $this->db->get("merkbarang");
return $data->row();
}
function insertMerk($newMerk){
$this->db->insert("merkbarang", $newMerk);
return true;
}
function editMerk($id, $newMerk){
$this->db->where("id", $id);
$this->db->update("merkbarang", $newMerk);
return true;
}
function deleteMerk($id){
$this->db->where("id", $id);
$this->db->delete("merkbarang");
return true;
}
function getTotalRows(){
$rows = $this->db->count_all("merkbarang");
return $rows;
}
function getMerkByPages($limit, $start){
$this->db->limit($limit, $start);
$query = $this->db->get("merkbarang");
if($query->num_rows() > 0){
foreach ($query->result() as $row){
$data[] = $row;
}
return $data;
}else{
return false;
}
}
View :
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="panel panel-danger">
<div class="panel-body">
<ul class="nav nav-pills nav-stacked">
<li role="presentation" class="active">Insert Merk</li>
</ul>
</div>
</div>
</div>
<div class="col-md-9">
<div class="panel panel-default">
<div class="panel-heading">
<strong>Merk</strong>
</div>
<div class="panel-body">
<div class="row" id="tabelBarang">
<div class="col-md-1 colBarang">
<strong>No</strong>
</div>
<div class="col-md-7 colBarang">
<strong>Merk</strong>
</div>
<div class="col-md-4 colBarang">
<strong>Action</strong>
</div>
</div>
<?php
$angka = 0;
foreach ($results as $row){
$id = $row->id;
$merk = $row->merk;
?>
<div class="row" id="tabelBarang">
<div class="col-md-1 colBarang">
<?php echo ++$angka; ?>
</div>
<div class="col-md-7 colBarang">
<?php echo $merk; ?>
</div>
<div class="col-md-2 colBarang">
<button type="button" class="btn btn-info btn-xs" aria-label="Left Align">
Edit
</button>
</div>
<div class="col-md-2 colBarang">
<button type="button" class="btn btn-danger btn-xs" aria-label="Left Align">
Delete
</button>
</div>
</div>
<?php
}
?>
<?php echo $links; ?>
</div>
</div>
</div>
</div>
</div>
The way I see it, there is nothing wrong in your code, that should definitely work, but I would suggest you to try CI's redirect() method in your delete function
public function deleteMerk($id){
$this->modelAdminMerk->deleteMerk($id);
redirect('controllername/merk');
}