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...
Related
I am studying about ajax datatabl. My AJAX datatable insert is not working. It has no error on console or whatsoever. It's just whenever I am inserting, the datatable is just refreshing. Is there anything that I missed? I have provided my codes below. Any help will be appreciated. Thank you very much.
This is the result whenever i'm adding. But it's not adding on database or whatsoever.
Views:
<div class="table-responsive">
<br/>
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
<br /><br />
<table id="user_datas" class="table table-bordered table-striped">
<thead>
<tr>
<th width="35%">Name</th>
<th width="35%">Email</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<!-- <input type="file" name="user_image" id="user_image" /> -->
<!-- <span id="user_uploaded_image"></span> -->
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
Ajax:
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
})
var dataTable = $('#user_datas').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"<?php echo base_url() . 'profile/fetch_user'; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 3],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
if(name != '' && email != '')
{
$.ajax({
url:"<?php echo base_url() . 'profile/user_action'?>",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
console.log(name);
console.log(email);
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Fields are Required");
}
});
});
</script>
Controller:
function fetch_user(){
$this->load->model("profiles");
$fetch_data = $this->profiles->make_datatables();
$data = array();
foreach($fetch_data as $row)
{
$sub_array = array();
$sub_array[] = $row->name;
$sub_array[] = $row->email;
$sub_array[] = '<button type="button" name="update" id="'.$row->id.'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval(isset($_POST["action"] )),
"recordsTotal" => $this->profiles->get_all_data(),
"recordsFiltered" => $this->profiles->get_filtered_data(),
"data" => $data
);
echo json_encode($output);
}
function user_action(){
if(isset($_POST["action"])){
if($_POST["action"] == "Add")
{
$insert_data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post("email.")
);
$this->load->model('profiles');
$this->profiles->insert_crud($insert_data);
echo 'Data Inserted';
}
}
function fetch_single_user()
{
$output = array();
$this->load->model("profiles");
$data = $this->profiles->fetch_single_user($_POST["user_id"]);
foreach($data as $row)
{
$output['name'] = $row->name;
$output['email'] = $row->email;
}
echo json_encode($output);
}
}
Model:
var $table = "userss";
var $select_column = array("id", "name", "email");
var $order_column = array(null, "name", "email", null, null);
function make_query()
{
$this->db->select($this->select_column);
$this->db->from($this->table);
if(isset($_POST["search"]["value"]))
{
$this->db->like("name", $_POST["search"]["value"]);
$this->db->or_like("email", $_POST["search"]["value"]);
}
if(isset($_POST["order"]))
{
$this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else
{
$this->db->order_by('id', 'DESC');
}
}
function make_datatables(){
$this->make_query();
if($_POST["length"] != -1)
{
$this->db->limit($_POST['length'], $_POST['start']);
}
$query = $this->db->get();
return $query->result();
}
function get_filtered_data(){
$this->make_query();
$query = $this->db->get();
return $query->num_rows();
}
function get_all_data()
{
$this->db->select("*");
$this->db->from($this->table);
return $this->db->count_all_results();
}
function insert_crud()
{
$this->db->insert('userss', $data);
}
What is your database structure? Is the table called userss or users?
$this->db->insert('userss', $data); <--Possible typo?
You likely will need to use the inspect feature of your browser and look at any responses under the network tab to see any errors.
I have a dropdown for students_id. Now I want to track the student name and class from another table when someone select any student id. I did something for that using ajax. Its not showing me any error in the console but just giving me null array and I think thats the problem related to the query. You can check my code below. :)
//Controller
public function create()
{
$students = Student::pluck('student_id', 'id')->all();
return view('admin.reports.create', compact('students'));
}
public function reportsAjax(Request $request) {
$students = DB::table("students")->where("student_id", $request->student_id)->pluck("student_id","id");
return json_encode($students);
}
//View and Ajax
<div class="form-group">
<label for="title">Select Student <span style="color: red">*</span></label>
<select name="student_id" class="form-control bg-dark text-white" >
<option>Select Student</option>
#foreach ($students as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="control-label">Student Full Name <span style="color: red">*</span></label>
<input name="std_name" type="text" required class="form-control" />
</div>
<div class="form-group">
<label class="control-label">Class <span style="color: red">*</span></label>
<input name="std_class" type="text" required class="form-control" />
</div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="student_id"]').on('change', function() {
var studentInfo = $(this).val();
if(studentInfo) {
$.ajax({
url: '/reports/ajax/'+studentInfo,
type: "GET",
dataType: "json",
success:function(data) {
$('input[name="std_name"]').empty();
$.each(data, function(key, value) {
$('select[name="std_name"]').append('<input value="'+ key +'">'+ value +'/>');
});
}
});
}else{
$('select[name="std_name"]').empty();
}
});
});
</script>
//Routes
Route::get('reports/ajax/{id}',array('as'=>'reports.ajax','uses'=>'ReportController#reportsAjax'));
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
]]);
Try this for your queries:
public function create()
{
$students = Student::all()->only(['student_id', 'id']);
return view('admin.reports.create', compact('students'));
}
public function reportsAjax(Request $request)
{
$students = DB::table('students')->where('student_id', $request->student_id)->only(['student_id','id']);
return response()->json($students, 200);
}
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 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);
}
}
}