I am having some problem in my login form like this
I want to display an individually error beside of each field
here is the controller
function index()
{
$this->form_validation->set_rules('username','Username','trim|required|exact_length[4]|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]|max_length[40]|xss_clean|callback_login');
$this->form_validation->set_rules('jabatan','Jabatan','trim|required|xss_clean');
if($this->form_validation->run() == false)
{
$this->load->view('login');
}
else
{
$this->load->view('welcome_message');
}
}
function login()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$jabatan = $this->input->post('jabatan');
$value = $this->m_login->login($username,$password,$jabatan);
if($value)
{
return true;
}
else
{
$this->form_validation->set_message('login', 'password salah');
//delete redirect() and showing blank white screen
return false;
}
I made the <?php echo form_error(); ?> beside each field
<?php echo form_open('c_login/login'); ?>
<table>
<tr>
<td>Username</td>
<td><?php $inusername=array('name' => 'username', 'class' => 'GUI'); echo form_input($inusername); ?></td>
<td class="error"><?php echo form_error('username'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php $inpassword=array('name' => 'password', 'class' => 'GUI', 'type' =>'password'); echo form_input($inpassword); ?></td>
<td class="error"><?php echo form_error('password'); echo $this->session->flashdata('login'); ?></td>
</tr>
<tr>
<td>Jabatan</td>
<td><?php $injabatan=array('keuangan' => 'keuangan', 'admin' => 'admin', 'hd' => 'head divisi', 'direktur' => 'direktur'); echo form_dropdown('jabatan',$injabatan,'keuangan','class = "gui"'); ?></td>
<td class="error"><?php echo form_error('jabatan'); ?></td>
</tr>
<tr>
<td></td>
<td><?php $insubmit=array('name' =>'login','class' =>'button','value' => 'Login'); echo form_submit($insubmit); echo nbs(); $inreset=array('name' =>'reset','class' =>'button','value' => 'Hapus'); echo form_reset($inreset); ?></td>
<td class="error"><?php echo form_error(); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
How come the form_error() function is not echoing anything when I click login with the username and password field left blank?
you know problem in your validation you're checking validation in index method of your class not in login method of your class and in your form you have given action to ci_login/login method which is redirecting if login is failed and its clearing form validation validate your fields on login method also and put all error message in session and display, i have made some changes in script have look here on this link Code modified
for this changes you have to use url helper
function index()
{
$this->form_validation->set_rules('username','Username','trim|required|exact_length[4]|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]|max_length[40]|xss_clean|callback_login');
$this->form_validation->set_rules('jabatan','Jabatan','trim|required|xss_clean');
if($this->form_validation->run() == false)
{
$this->load->view('login');
}
else
{
//to check if the validation run correctly
//$this->load->view('welcome_message');
$username = $this->input->post('username');
$password = $this->input->post('password');
$jabatan = $this->input->post('jabatan');
$value = $this->m_login->login($username,$password,$jabatan);
if($value)
{
redirect('welcome_message');
//return true;
}
else
{
$this->form_validation->set_message('login', 'password salah');
redirect('c_login',$login); //i want to pass $login into login form, then print
return false; //them as a form_error
}
}
}
<?php echo form_open(uri_string()); ?>
<table>
<tr>
<td>Username</td>
<td><?php $inusername=array('name' => 'username', 'class' => 'GUI'); echo form_input($inusername); ?></td>
<td class="error"><?php echo form_error('username'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php $inpassword=array('name' => 'password', 'class' => 'GUI', 'type' =>'password'); echo form_input($inpassword); ?></td>
<td class="error"><?php echo form_error('password'); echo $this->session->flashdata('login'); ?></td>
</tr>
<tr>
<td>Jabatan</td>
<td><?php $injabatan=array('keuangan' => 'keuangan', 'admin' => 'admin', 'hd' => 'head divisi', 'direktur' => 'direktur'); echo form_dropdown('jabatan',$injabatan,'keuangan','class = "gui"'); ?></td>
<td class="error"><?php echo form_error('jabatan'); ?></td>
</tr>
<tr>
<td></td>
<td><?php $insubmit=array('name' =>'login','class' =>'button','value' => 'Login'); echo form_submit($insubmit); echo nbs(); $inreset=array('name' =>'reset','class' =>'button','value' => 'Hapus'); echo form_reset($inreset); ?></td>
<td class="error"><?php echo form_error(); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
index will not execute when login does.
If appears that maybe you think the set_rules() functions will execute when you submit the form. They won't. The form will submit to 'c_login/login', which is the login() function inside your c_login controller.
You need to move your form validation logic into login(), and have index() just echo the view for the first time.
Your Controller
function index(){
$this->load->view('login');
}
function login(){
$this->form_validation->set_rules('username','Username','trim|required|exact_length[4]|xss_clean');
$this->form_validation->set_rules('password','Password','required|xss_clean|correct');
$this->form_validation->set_rules('jabatan','Jabatan','trim|required|xss_clean');
if($this->form_validation->run() == false){
//your validation messages will be taken care of.
$this->load->view('login');
}
else{
$p = $this->input->post();
if($this->m_login->login($p['username'],$p['password'],$p['jabatan'])){
//redirect() user to logged in area.
}
else{
$this->form_validation->set_message('login', 'password salah');
$this->load->view('login');
}
}
}
Also, you shouldn't be trimming passwords. The space character is a perfectly valid suffix or prefix in a password. I've removed trim for you. I've also removed the min_length and max_length. This is something you'd want to enforce on a signup page, are you sure it really adds any value on a login page?
You need to supply form_error() with the field:
<?php echo form_error('username'); ?>
See more details here
It looks to me that you have a big misunderstanding on how these things work. First of all, you don't need that redirect() call in login(). The redirect() functions will redirect the user to another page, and since neither CodeIgniter nor PHP keep an object between page requests, you'd lose everything (e.g. The form validation object and its error messages).
Also, you might want to prefix that login() method with an underscore (_), so that no one can access it through an HTTP request.
You should probably submit the form to the index() method instead of login(). Then, make sure you only run the validation on a POST request.
function index()
{
if ($_POST)
{
// run validation here
}
// ...
}
**Simple form validation, image upload and captcha using codeigniter libraries**
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Loginmodel');
}
public function index()
{
$config = array(
'img_path' => 'uploadss/',
'img_url' => base_url().'uploadss/',
'font_path' => base_url().'system/fonts/texb.ttf',
'img_width' => '200',
'img_height' => 90,
'word_length' => 3,
'font_size' => 25
);
$captcha = create_captcha($config);
// Unset previous captcha and set new captcha word
$this->session->unset_userdata('captchaCode');
$this->session->set_userdata('captchaCode', $captcha['word']);
// Pass captcha image to view
$fetch['captchaImg'] = $captcha['image'];
$fetch['data'] = $this->Loginmodel->alldata();
$this->load->view('login',$fetch);
}
public function loginerror()
{
$this->form_validation->set_rules('fname','first name','required|alpha');
$this->form_validation->set_rules('lname','last name', 'required');
$this->form_validation->set_rules('mobile', 'Mobile', 'required|numeric');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('companyname', 'Companyname', 'required');
$this->form_validation->set_rules('designation', 'Designation', 'required');
$this->form_validation->set_rules('companysize', 'Companysize', 'required|numeric');
if($this->form_validation->run())
{
$inputCaptcha = $this->input->post('captcha');
$sessCaptcha = $this->session->userdata('captchaCode');
if($inputCaptcha === $sessCaptcha)
{
echo 'Captcha code matched.';
$fname = $this->input->post('fname');
$lname = $this->input->post('lname');
$mobile = $this->input->post('mobile');
$email = $this->input->post('email');
$password = $this->input->post('password');
$companyname = $this->input->post('companyname');
$designation = $this->input->post('designation');
$companysize = $this->input->post('companysize');
$checkmobile = $this->Loginmodel->checkmobile($mobile,$email);
if($checkmobile)
{
$this->session->set_flashdata("danger","Mobile Number or Email exist.....");
return redirect('Login/index');
}
else
{
$insertdata = $this->Loginmodel->insert($fname,$lname,$mobile,$email,$password,$companyname,$designation,$companysize);
$this->session->set_flashdata("success","Record Inserted");
return redirect('Home/indexhome');
}
// }
// else
// {
// $this->session->set_flashdata("danger","Please fill all the values properly");
// $this->index();
// }
}
else
{
echo 'Captcha code does not match, please try again.';
$this->index();
}
}
else
{
$this->session->set_flashdata("danger","Please fill all the values properly");
$this->index();
}
}
public function refresh(){
// Captcha configuration
$config = array(
'img_path' => 'uploadss/',
'img_url' => base_url().'uploadss/',
'font_path' => base_url().'system/fonts/texb.ttf',
'img_width' => '200',
'img_height' => 90,
'word_length' => 3,
'font_size' => 25
);
$captcha = create_captcha($config);
$this->session->unset_userdata('captchaCode');
$this->session->set_userdata('captchaCode',$captcha['word']);
echo $captcha['image'];
}
public function upload($id)
{
if(!empty($_FILES['imagename']['name']))
{
$config['upload_path'] = 'uploadss/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['imagename']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('imagename'))
{
$uploadData = $this->upload->data();
$imagename = $uploadData['file_name'];
}
else
{
echo "not upload";
}
}
else
{
echo "error";
}
$this->load->view('uploadimage');
}
public function uploadimageerror()
{
if(!empty($_FILES['imagename']['name']))
{
$config['upload_path'] = 'uploadss/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['imagename']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('imagename'))
{
$uploadData = $this->upload->data();
$imagename = $uploadData['file_name'];
}
else
{
echo "not upload";
}
}
else
{
echo "error";
}
}
public function deletedata($id)
{
$dele = $this->Loginmodel->delete($id);
return redirect('Login/index');
}
}
?>
Related
I want to validate a form to make sure a user entered something in the description field in this situation form validation is correct.
But,
Here , I pass value to function 2 by fetching values from function 1
When function 2 loads first time it fetch data and display the values (OK)
But When function 2 resubmit for validation and submision data these valitable get empoty and it throw the error Message: Undefined variable: query (ERROR)
I don't know how to do this, hehe. I'm just a newbie PHP programmer.
Here's what I have so far:
function 1
public function ask()
{
$this->load->model('MainM');
$this->load->library('form_validation');
$this->form_validation->set_rules('index', 'AL Index', 'trim|required|min_length[7]|max_length[7]');
if($this->form_validation->run() == FALSE) {
$this->load->view('enterindex');
}else{
$query = null; //emptying in case
$index = $this->input->post("index"); //getting from post value
$query = $this->db->get_where('tbl_reg', array('reg_index' => $index));
$count = $query->num_rows(); //counting result from query
if ($count == 1) {
$data['query'] = $this->MainM->getregdata($index);
$result = $this->load->view('submitques',$data);
}else{
$data = array();
$data['error'] = 'error';
$this->load->view('enterindex', $data);
}
}
function 2
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
Actully you have $data variable put in else part so thats why this error appeared you need to define before loop.
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
// define here before check condtions
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
If you wish to use the posted $data variable on false condition, you could moving it up outside the validation block :
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
Try with This Code:
First Add Form Library to config/autoload.php
$autoload['libraries'] = array('database','form_validation');
html Code
This is view file login.php
<?php echo form_open('action_controller_name', array('class' => '', 'enctype' => 'multipart/form-data', 'role' => 'form', 'name' => 'myform', 'id' => 'myform')); ?>
<div class="form-group">
<label class="control-label" for="mobile">Mobile-No</label>
<input type="text" name="mobile" value="" placeholder="Enter Mobile No" id="mobile" class="form-control" />
<label class="error"><?php echo form_error('mobile'); ?></label>
</div>
<div class="form-group">
<label class="control-label" for="password">Password</label>
<input type="password" name="password" value="" placeholder="Password" id="password" class="form-control" />
<label class="error"><?php echo form_error('mobile'); ?></label>
</div>
<input type="submit" value="Login" class="btn btn-gray" id="submit" />
<a class="forgotten" href="<?php echo base_url('login/forgot_password'); ?>" style="font-size: 13px;">Forgot Password</a>
<?php
echo form_close();
?>
My Action Controller
public function action_controller_name() {
$this->load->helper(array('form')); // Load Form Library
$this->load->library('form_validation'); // Load Form Validaton Library
$this->form_validation->set_rules('mobile', 'mobile', 'required', array('required' => 'Please Enter Mobile Number.'));
$this->form_validation->set_rules('password', 'Password', 'required', array('required' => 'Please Enter passsword.'));
if ($this->form_validation->run() === TRUE) { // Check validation Run
// Your Login code write here
} else {
$this->load->view('login', $this->data);
}
}
Try this code.You can keep variable value if validation fails in codeigniter successfully.
I've got a really weird issue that I can't seem to figure out or understand. So essentially I have a to grab the ID passed through the Codeigniter URI, have it populate a hidden form, and then submitted. However when I submit the form as hidden, it comes back saying the data is NULL. I have tried and changed it to form_input and it works fine. Can anyone help me or explain to me why this is the case?
I have tried the following solutions.
URL
http://localhost/list/players/add/1/
where I want URI 3 ('1') to pass on to the form and submitted.
Solution 1 - Having the URI pass straight to data array
Controller
function add() {
if($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$league_id = $this->uri->segment(3);
$data = array(
'leagues_id' => $league_id,
);
if($this->_insert($data)){
return $query;
}
redirect ('/players/');
}
}
Solution 2 - Grabbing the URI and fill a hidden form
Controller
function add() {
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
if($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data = array(
'leagues_id' => $this->input->post('leagues_id'),
);
if($this->_insert($data)){
return $query;
}
redirect ('/players/');
}
}
View
<?php
echo form_open('players/add/');
?>
<?php
echo "<br>";
echo "<br>";
echo "League Name";
echo "<br>";
foreach ($leagues_list->result() as $row) {
$league_id = $row->id;
$league_name = $row->league_name;
echo $league_name;
$data = array( 'name' => 'leagues_id',
'value' => $league_id,
);
echo form_hidden($data);
}
echo "<br>";
echo "<br>";
$data = array( 'value' => 'Set Player',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
In both scenarios, on submit it comes back with an error saying leagues_id is NULL. Now I have tried in Solution 2 to change from 'form_hidden' to 'form_input' and straight away clicking submit and it works fine.
Can anyone help me or advise why this is the case?
Many thanks.
If you want to add a parameter to your controller's function, you have to add it to: function func($parameter = 0) (= 0 is optional for default value).
In this case you can access the parameter by $parameter.
In your View file, you can open your form to post to the current url. For this you need to load the url helper in your controller: $this->load->helper('url'); (or you can autoload it in application/autoload.php).
Your form_hidden declaration was bad too. If you want to declare it with array(), then you have to use this syntax:
$data = array(
'name' => 'John Doe',
'email' => 'john#example.com'
);
echo form_hidden($data);
// Would produce:
<input type="hidden" name="name" value="John Doe" />
<input type="hidden" name="email" value="john#example.com" />
More information on Form helper: https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
For the right solution, try this:
Controller
function add($league_id = 0)
{
if($league_id != 0)
{
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
if($this->form_validation->run() == FALSE)
{
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
}
else
{
$data = array(
'leagues_id' => $this->input->post('leagues_id'),
);
if($this->_insert($data))
{
return $query;
}
redirect ('/players/');
}
}
View
<?php
echo form_open(current_url());
echo "<br /><br />";
echo "League Name <br />";
foreach ($leagues_list->result() as $row)
{
$league_id = $row->id;
$league_name = $row->league_name;
echo $league_name;
echo form_hidden('leagues_id', $league_id);
}
echo "<br /><br />";
$data = array(
'value' => 'Set Player',
'name' => 'submit',
'class' => 'submit-btn'
);
echo form_submit($data);
echo form_close();
?>
I'm trying to create captcha, the image is shown as expected, but when i pass into controller why the string that i input is different with session user data that i set in earlier.
PFB my code.
View.
<?php echo $captcha_img;?>
<input type="text" id="captcha" name="captcha" placeholder="Input Code Above">
<?php echo form_error('captcha', '<p class="field_error">', '</p>');?>
Controller (config)
public function captcha_config() {
$vals = array(
'img_path' => './assets/files/captcha/',
'img_url' => base_url().'assets/files/captcha/',
'img_width' => 150,
'img_height' => 30
);
$cap = create_captcha($vals);
$image = $cap['image'];
$this->session->set_userdata('capt',$cap['word']);
//$data['captcha_img'] = $cap['image'];
return $image;
}
Controller (Index)
public function index() {
if ($this->session->userdata('login') == TRUE)
{
redirect('Buser');
}
else
{
$data['title'] = 'Dashboard';
$data['subtitle'] = 'Log In';
$this->captcha_config();
$data['captcha_img'] = $this->captcha_config();
$this->load->view('Backend/login', $data);
}
Controller (Process)
public function process_login() {
$data['title'] = 'Dashboard';
$data['subtitle'] = 'Log In';
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('captcha', 'Captcha', 'required' );
$this->captcha_config();
$data['captcha_img'] = $this->captcha_config();
if ($this->form_validation->run() == TRUE)
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$captcha = $this->input->post('captcha');
echo $captcha;
echo "<br>";
echo $this->session->userdata('capt');
}
}
result:
Drd27VZE <--- this one is the captcha
VzU90odU <--- this one is the session user data 'capt'
I've been trying using with separate code (example that i got from google) it works, but i don't know why it's not working with this code.
you can create a captcha function in helper
Helper
function generate_captcha()
{
$options = array(
'img_path' => 'img/captcha/',
'img_url' => base_url().'img/captcha/',
'img_width' => '150',
'img_height'=> '50',
'expiration'=> 3600,
'word' => generate_random_password(4)
);
return create_captcha($options);
}
function generate_random_password( $max_length = 8 )
{
$pass = '';
$dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$dict_size = strlen($dict);
for($i = 0;$i<$max_length;$i++){
$pass .= $dict[rand(0,$dict_size-1)];
}
return strtoupper($pass);
}
In your view, you call a generate_captcha if the user put a wrong user ou pass
<?php if( ! empty( $attempts_number ) && ((int)$attempts_number >= 3) ) { ?>
<?php $captcha = generate_captcha(); ?>
<?php $this->session->set_userdata(array(
'captchaword' => $captcha['word']
)); ?>
<?php echo $captcha['image']; ?>
<label><?php echo $this->lang->line('captcha_text'); ?>:</label>
<?php echo form_input(array('class'=>'required','maxlength'=>4,'name'=>'captcha'));?>
<?php } ?>
Finally i solve my problem,
problem when i create function for captcha i don't have to call again in the process function
public function process_login() {
$data['title'] = 'Dashboard';
$data['subtitle'] = 'Log In';
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('captcha', 'Captcha', 'required' );
**$this->captcha_config(); <---- I Remove this one
$data['captcha_img'] = $this->captcha_config(); <---- and also remove this one**
if ($this->form_validation->run() == TRUE)
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$captcha = $this->input->post('captcha');
echo $captcha;
echo "<br>";
echo $this->session->userdata('capt');
}
}
I have an issue where every time I click on login it just takes me to my page it seems to not be checking to see if the username or password was entered. I am not sure what the issue is I changed the line if ($this->form_validation->run() == FALSE) to true and then I just get redirected back to the login when I enter correct password. I think it is something simple I am just missing. If anyone has an idea any direction would help in the mean time I will keep figuring it out.
Controllers
Verifylogin.php controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
if($this->form_validation->run() == false)
{
//Field validation failed. User redirected to login page
$this->load->view('person_view');
}
else
{
//Go to private area
redirect('Person', 'refresh');
}
}
public function check_database() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_view.php');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->admin_database->login($data);
if($result == TRUE){
$sess_array = array(
'username' => $this->input->post('username')
);
}
}
}
}
Person.php controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Person extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('person_model','callin_list');
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$this->load->view('person_view');
}else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function ajax_list()
{
$list = $this->callin_list->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $callin_list) {
$no++;
$row = array();
$row[] = $callin_list->Date_Scheduled;
$row[] = $callin_list->Employee_Name;
$row[] = $callin_list->Employee_Number;
$row[] = $callin_list->Time_Reported;
$row[] = $callin_list->Reason;
$row[] = $callin_list->Scheduled_Area;
$row[] = $callin_list->Contact;
$row[] = $callin_list->Comments;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void()" title="Edit" onclick="edit_person('."'".$callin_list->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm btn-danger" href="javascript:void()" title="Hapus" onclick="delete_person('."'".$callin_list->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->callin_list->count_all(),
"recordsFiltered" => $this->callin_list->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->callin_list->get_by_id($id);
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'Date_Scheduled' => $this->input->post('Date_Scheduled'),
'Employee_Name' => $this->input->post('Employee_Name'),
'Employee_Number' => $this->input->post('Employee_Number'),
'Time_Reported' => $this->input->post('Time_Reported'),
'Reason' => $this->input->post('Reason'),
'Scheduled_Area' => $this->input->post('Scheduled_Area'),
'Contact' => $this->input->post('Contact'),
'Comments' => $this->input->post('Comments'),
);
$insert = $this->callin_list->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'Date_Scheduled' => $this->input->post('Date_Scheduled'),
'Employee_Name' => $this->input->post('Employee_Name'),
'Employee_Number' => $this->input->post('Employee_Number'),
'Time_Reported' => $this->input->post('Time_Reported'),
'Reason' => $this->input->post('Reason'),
'Scheduled_Area' => $this->input->post('Scheduled_Area'),
'Contact' => $this->input->post('Contact'),
'Comments' => $this->input->post('Comments'),
);
$this->callin_list->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
$this->callin_list->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
//validation section were user must enter data in all fields
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('Date_Scheduled') == '')
{
$data['inputerror'][] = 'Date_Scheduled';
$data['error_string'][] = 'Date_Scheduled is required';
$data['status'] = FALSE;
}
if($this->input->post('Employee_Name') == '')
{
$data['inputerror'][] = 'Employee_Name';
$data['error_string'][] = 'Employee_Name is required';
$data['status'] = FALSE;
}
if($this->input->post('Employee_Number') == '')
{
$data['inputerror'][] = 'Employee_Number';
$data['error_string'][] = 'Employee_Number is required';
$data['status'] = FALSE;
}
if($this->input->post('Time_Reported') == '')
{
$data['inputerror'][] = 'Time_Reported';
$data['error_string'][] = 'Time_Reported is required';
$data['status'] = FALSE;
}
if($this->input->post('Reason') == '')
{
$data['inputerror'][] = 'Reason';
$data['error_string'][] = 'Reason is required';
$data['status'] = FALSE;
}
if($this->input->post('Scheduled_Area') == '')
{
$data['inputerror'][] = 'Scheduled_Area';
$data['error_string'][] = 'Scheduled_Area is required';
$data['status'] = FALSE;
}
if($this->input->post('Contact') == '')
{
$data['inputerror'][] = 'Contact';
$data['error_string'][] = 'contact is required';
$data['status'] = FALSE;
}
if($this->input->post('Comments') == '')
{
$data['inputerror'][] = 'Comments';
$data['error_string'][] = 'Comments is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
login_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
* Description: Login model class
*/
class Login_model extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate(){
// grab user input
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
// Prep the query
$this->db->where('username', $username);
$this->db->where('password', $password);
// Run the query
$query = $this->db->get('users');
// Let's check if there are any results
if($query->num_rows() == 1)
{
// If there is a user, then create session data
$row = $query->row();
$data = array(
'userid' => $row->userid,
'fname' => $row->fname,
'lname' => $row->lname,
'username' => $row->username,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
// If the previous process did not validate
// then return false.
return false;
}
}
?>
login_view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login Form</title>
<style type="text/css">
.content{
margin-left: 400px;
margin-top: 300px;
}
.btn{
width:242px;
height: 50px;
}
#label{
font-size: 24px;
font-weight: normal;
}
</style>
<link href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css')?>" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="content">
<h1>DC399 Callin Login Page</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('verifylogin'); ?>
<label id="label"for="username">Username:</label><br>
<input type="text" size="20" id="username"style="width: 239px; height: 40px; margin-right: 20px;"name="username"/>
<br/>
<label id="label" for="password">Password:</label><br>
<input type="password" size="20" id="passowrd" style="width: 239px; height: 40px; margin-right: 20px;"name="password"/>
<br/><br>
<input class="btn btn-success" type="submit" value="Login"/>
</form>
</div>
</div>
<script src="<?php echo base_url('assets/jquery/jquery-2.1.4.min.js')?>"></script>
<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>"></script>
</body>
</html>
Use $this->form_validation->run() === FALSE instead, with 3 = signs.
You are sending the data to verifylogin/index and any moment are loading the rules to check and validate neither are checking from the database. That's the problem.
I am new in codeigniter. I build a cms with codeigniter for blog. But when i want edit a article post and want to save it, it create new one post not update old post which i edited.
Please help me.
My Article Edit crontroller:
public function edit ($id = NULL)
{
// Fetch a article or set a new one
if ($id) {
$this->data['article'] = $this->article_m->get($id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// categories for dropdown
$this->data['all_categories'] = $this->article_m->join();
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->article_m->array_from_post(array(
'title',
'extra_title',
'slug',
'image',
'category_id',
'body',
'pubdate'
));
$this->article_m->save($data, $id);
redirect('admin/article');
}
// Load the view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/_layout_main', $this->data);
}
My Models:
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE){
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL){
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function get_new ()
{
$article = new stdClass();
$article->title = '';
$article->extra_title = '';
$article->slug = '';
$article->image = '';
$article->category_id = '';
$article->body = '';
$article->pubdate = date('Y-m-d');
return $article;
}
public function join()
{
$this->db->select('name,categories.id as category_id');
$this->db->from($this->_table_name);
$this->db->join('categories', 'categories.id = category_id','right');
$Q = $this->db->get();
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['category_id']] = $row['name'];
}
}
$Q->free_result();
return $data;
}
My View:
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('admin/article/edit'); ?>
<table class="table">
<tr>
<td>Publication date</td>
<td><?php echo form_input('pubdate', set_value('pubdate', $article->pubdate), 'class="datepicker"'); ?></td>
</tr>
<tr>
<td>Category</td>
<td><?php
$js = 'id="category_id" onChange="some function();"';
echo form_dropdown('category_id', $all_categories, set_value('category_id', $article->category_id), $js); ?></td>
</tr>
<tr>
<td>Title</td>
<td><?php echo form_input('title', set_value('title', $article->title)); ?></td>
</tr>
<tr>
<td>Extra Title (Optional)</td>
<td><?php echo form_input('extra_title', set_value('extra_title', $article->extra_title)); ?></td>
</tr>
<tr>
<td>Slug</td>
<td><?php echo form_input('slug', set_value('slug', $article->slug)); ?></td>
</tr>
<tr>
<td>Upload Image</td>
<td>
<div class="input-append">
<?php echo form_input('image', set_value('image', $article->image),'id="fieldID"'); ?>
Select
</div>
</td>
</tr>
<tr>
<td>Body</td>
<td><?php echo form_textarea('body', set_value('body', $article->body), 'class="tinymce"'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<?php echo form_close();?>
Please Help Me.
You have to pass the id to the controller. In your view you are telling the form to submit to
article/edit but not the id.
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('admin/article/edit/'.$article->id); ?>
...
You'll probably get some warnings if $article is not set, so you may want to put in some checks for when you're adding a new item.