not able to load validation config file in codeigniter? - codeigniter

I have created an application in CodeIgniter. I'm trying to insert validation in a form. As I will have many forms in my application, so I'm trying to do it with validation config file.
I have created config file in application/config/form_validation.php. I have also autolaoded config file by adding $autoload['config'] = array('form_validation');
Still, my Validation is not working properly it is always returning boolean false
Below code for the same
form_validation.php file
<?php
$config= array(
'Reservation' => array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'required|max_length[50]|min_length[4]|trim|htmlspecialchars|alpha'
),
array(
'field' => 'date',
'label' => 'Date',
'rules' => 'required|trim|htmlspecialchars',
'errors'=> ['required'=>'You must provide a %s for the reservation.']
),
array(
'field' => 'no_people',
'label' => 'No of People',
'rules' => 'required|trim|htmlspecialchars'
)
)
);
?>
index.php - View
<div class="book-reservation wow slideInUp" data-wow-duration="1s" data-wow-delay=".5s">
<?php echo "<script>alert('".validation_errors()."')</script>"; ?>
<?php echo form_open('Entry/Reservation'); ?>
<div class="col-md-12 form-left">
<label><i class="glyphicon glyphicon-calendar"></i>Enter Name:</label>
<input type="text" name='name' value="<?php echo set_value('name'); ?>">
</div>
<div class="col-md-3 form-left">
<label><i class="glyphicon glyphicon-calendar"></i> Date :</label>
<input type="date" name='date' value="<?php echo set_value('date'); ?>">
</div>
<div class="col-md-3 form-left">
<label><i class="glyphicon glyphicon-user"></i> No.of People :</label>
<select class="form-control" name='no_people' value="<?php echo set_value('no_people'); ?>">
<option>1 Person</option>
<option>2 People</option>
<option>3 People</option>
<option>4 People</option>
<option>5 People</option>
<option>More</option>
</select>
</div>
</div>
Entry.php - Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Entry extends CI_Controller {
public function __construct()
{
Parent::__construct();
$this->load->model('Restaurant');
}
public function index()
{
$this->load->view('index');
}
public function Reservation()
{
var_dump($this->form_validation->run('Reservation'));
die;
if($this->form_validation->run() == FALSE)
{
redirect();
}
else
{
#getting values of form
$data['a'] = array(
'Person_Name' => $this->input->post('name'),
'Phone_Number' => $this->input->post('phone'),
'Reservation_Date' => $this->input->post('date'),
'No_People' => $this->input->post('no_people'),
'Reservation_Time' => $this->input->post('time')
);
$data['a'] = $this->security->xss_clean($data['a']); #cleaning data
#calling model
//echo"<pre>";print_r($data['a']);
//die;
if($this->Restaurant->insert_entries($data['a']))
{
$this->session->set_flashdata('message','Your Reservation has accepted, We will call you back shortly.');
redirect();
}
else
{
$this->session->set_flashdata('message','Some techincal issue occured, your reservation did not complete.');
}
}
}
}

Error in below code as it is not redirecting anywhere
if($this->form_validation->run() == FALSE)
{
redirect();
}
Correct Answer:
if($this->form_validation->run() == FALSE)
{
$this->load->view('index');
}

Related

Capcha image is showing blank using codeigniter

I have installed xampp with upgraded php 7.4.10 version because of the higher version installed captcha is not showing image showing blank (code is blank in white background).
enter image description here
Please find below screenshot of code
Javascript of html file login.phtml
if(document.frm_login.password.value!="")
{
var hash = CryptoJS.HmacSHA256(document.frm_login.password.value, "");
$('#passwords').text('');
document.frm_login.password.value=mixUpValues(hash.toString(),
document.frm_login.keyy.value,document.frm_login.keyy1.value);
}
if(document.frm_login.vercode.value==""||document.frm_login.vercode.value==null)
{
$('#captcha-code').text('Please enter code!');
$('#vercode').focus();
return false;
}
if(document.frm_login.vercode.value!=""||document.frm_login.vercode.value!=null)
{
$('#captcha-code').text('');
}
Html code of login.phtml
<div class="form-group captcha">
<?php echo $this->form->vercode; ?>
<p><span><img src="<?php echo $this->baseUrl('cool_capcha/captcha.php'); ?>"
id="captcha" /></span>
<a onclick="document.getElementById('captcha').src='<?php echo $this-
>baseUrl('cool_capcha/captcha.php'); ?>?'+Math.random();
document.getElementById('vercode').focus();"id="change-image" class="menu4
refresh" style="cursor:pointer">
<img src="./images/refress.png" class ="refresh" id="refresh" /></a></p>
<div class="clearfix"></div><span class="require" id="captcha-code">
</span>
</div>
Forms Auth.php
$this->addElement('text', 'vercode', array(
//'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'class' => 'form-control captchain',
'placeholder' => 'Captcha',
'autocomplete' => 'off',
'decorators'=>Array(
'ViewHelper',
'Errors',
),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
Controller AuthController function loginAction()
$captcha = new Zend_Session_Namespace('captcha');
$captcha->captcha = session_id();
if($dataform['vercode'] != $_SESSION["vercode"]){
$msg="Please enter a correct code!";
$this->view->assign('msg', $msg);
return false;
}

How to pass in user id into foreach loop?

I'm a novice when it comes to PHP and Laravel and am embarrassed that I haven't figured this out yet. I'm trying to provide an option for my user to import their database into the application. However, I need to attach a user id to each row so it can be saved with that user. I've tried multiple attempts to grab that user id and pass it into the foreach loop so it can be saved. Any guidance I can receive, I'd be most grateful. I am using Maatwebsite/Laravel-Excel facade.
Here is my Controller:
class ImportController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function importExcel()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$user = Auth::user();
$data['user_id'] = $user->id;
$insert[] = [
'user_id' => $value->user_id,
'first_name' => $value->first_name,
'last_name' => $value->last_name,
'title' => $value->title,
'level' => $value->level,
'company' => $value->company,
'email' => $value->email,
'address_1' => $value->address_1,
'address_2' => $value->address_2,
'city' => $value->city,
'state' => $value->state,
'zip_code' => $value->zip_code,
'office_tel' => $value->office_tel,
'mobile_tel' => $value->mobile_tel,
'member_since'=> $value->member_since
];
}
if(!empty($insert)){
DB::table('members')->insert($insert);
Session::flash('flash_message', 'Database successfully imported!');
}
}
}
return back();
}
}
Here is my route:
Route::post('importExcel', 'ImportController#importExcel');
Here is my view:
<button type="button" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#importExcel">Import</button>
<div class="modal fade" id="importExcel" tabindex="-1" aria-labelledby="importExcelLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Import Your Database</h4>
</div>
<div class="modal-body">
<p>Click browse to import your database. Only Microsoft Excel extensions are acceptable. Please label your columns as follows:</p>
<ul>
<li>user_id (leave this column empty)</li>
<li>first_name</li>
<li>last_name</li>
<li>title</li>
<li>level</li>
<li>company</li>
<li>address_1</li>
<li>address_2</li>
<li>city</li>
<li>state</li>
<li>zip_code</li>
<li>office_tel</li>
<li>mobile_tel</li>
<li>member_since</li>
</ul>
<form action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
<input type="file" name="import_file" />
<input type="hidden" name="_token" value="{{csrf_token()}}">
<button type="submit" class="btn btn-primary">Import File</button>
</form>
</div><!-- /.modal-body-->
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Close</button>
</div><!-- /.modal-footer-->
</div><!-- /.modal-content-->
</div><!-- /.modal-dialog-->
</div><!-- /.modal-->
Here is my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
protected $fillable = [
'user_id',
'first_name',
'last_name',
'title',
'level',
'company',
'email',
'address_1',
'address_2',
'city',
'state',
'zip_code',
'office_tel',
'mobile_tel',
'member_since' ];
}
First of all: Where do you set $insert? You have to set this variable with the data you like to import. Despite of that you can try the following:
If I understand you right, the database-field user_id should contain the ID of the logged in user - if so, try in your controller the following in importExcel (see comment):
public function importExcel(Request $request)
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$user = Auth::user();
$data['user_id'] = $user->id;
[
'user_id' => $user->id, // Access here the userId of the logged in user
'first_name' => $value->first_name,
'last_name' => $value->last_name,
'title' => $value->title,
'level' => $value->level,
'company' => $value->company,
'email' => $value->email,
'address_1' => $value->address_1,
'address_2' => $value->address_2,
'city' => $value->city,
'state' => $value->state,
'zip_code' => $value->zip_code,
'office_tel' => $value->office_tel,
'mobile_tel' => $value->mobile_tel,
'member_since'=> $value->member_since
];
}
if(!empty($insert)){
DB::table('members')->insert($insert);
Session::flash('flash_message', 'Database successfully imported!');
}
}
}
return back();
}
Hope that helps :)

how does one load a div using its id to a view?

how does one load a div using its id to a view?
this is my view
<div id="register" class="animate form">
<section class="login_content">
<form <?php echo form_open('User/register'); ?>
<h1>Create Account</h1>
<div class="inputlogin">
<div class="form-group">
how will i pass it to
if ($this->form_validation->run() === false) {
// validation not ok, send validation errors to the view
$index['title']="Welcome to Hoovie";
$index['mainContent']="login";
$index['results'] = $this->users_model->get_category();
$this->load->view('includes/redirect', $index, $data);
First, form_open tag makes <form> so you can't echo it inside of form it would look like <form <form>>
here is example of login form inside of view:
echo form_open('path/to/controller');
echo form_input(array(
'name' => 'username',
'class' => 'form-control input-lg',
'placeholder' => 'username'
));
echo form_password(array(
'name' => 'password',
'class' => 'form-control input-lg',
'placeholder' => 'password'
));
echo form_submit(array(
'name' => 'LoginSubmit',
'class' => 'btn btn-lg btn-info',
'value' => 'Login'
));
echo form_close();}
After that inside of your controller you have to activate form_validation library if it is not auto-loaded and then you have to set rules for your inputs
example :
$dugme = $this->input->post('LoginSubmit');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if(isset($dugme) && $this->form_validation->run()){
//if everything ok, do something
}
else {
//if validation did not pass load view
$this->load_view('login'); }
and after that inside of view you have to echo errors
//I am using bootstrap so alert-danger will show this div with red background
<?php echo validation_errors('<div class="alert alert-danger">','</div>');?>
you can check more about form validation here :
Codeigniter 3: https://www.codeigniter.com/userguide3/libraries/form_validation.html
Codeigniter 2: https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

How to reuse form in codeigniter for update and add

Hello i want to reuse a form in codeigniter but problem is the update form is populated one the page has load. Here is a sample form.
<?php
$attributes = array('class' => 'form-horizontal', 'id' => 'addPersonnel');
echo form_open($form_submission, $attributes);
?>
<input type="text" name="name" value="<?php echo set_value('name')?"> >
<input type="text" name="rank" value="<?php echo set_value('rank')?"> >
<button type="submit" class="btn btn-primary">Save</button>
<?php echo form_close()?>
My problem here lies in the set_value() method of the form_validation class since it will have conflict with populating the form if updating.
In your controller update function add a condition like:
if ($this->input->server('REQUEST_METHOD') === 'POST') {
$this->_get_userinfo_form_fields();
} else {
$this->_get_userinfo_form_fields($user_data); //$user_data from database
}
For add function you can directly call - $this->_get_userinfo_form_fields();
Then declare a function as below:
protected function _get_userinfo_form_fields($user_data = array()) {
$this->data['rank'] = array(
'placeholder' => 'Rank',
'name' => 'rank',
'id' => 'rank',
'class' => '',
'value' => isset($user_data['rank']) ? $user_data['rank'] :set_value('rank',$this->input->post('rank',TRUE)),
'style' => '',
);
//Add rest of the fields here like the above one
}
In view file add code like:
<?php echo form_input($rank);?>

Model not inserting array data

When I submit my form my controller[] array post does not work throws errors.
Error 1
A PHP Error was encountered Severity: Notice Message: Array to string
conversion Filename: mysqli/mysqli_driver.php Line Number: 544
Error Number: 1054 Unknown column 'Array' in 'field list' INSERT INTO
user_group (name, controller, access, modify) VALUES
('Admin', Array, '1', '1') Filename:
C:\Xampp\htdocs\riwakawebsitedesigns\system\database\DB_driver.php
Line Number: 331
It is not inserting the controller names. Not sure best way to fix?
Model
<?php
class Model_user_group extends CI_Model {
public function addUserGroup($data) {
$data = array(
'name' => $this->input->post('name'),
'controller' => $this->input->post('controller'),
'access' => $this->input->post('access'),
'modify' => $this->input->post('modify')
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}
?>
Controller
<?php
class Users_group extends Admin_Controller {
public function index() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$user_group_info = $this->model_user_group->getUserGroup($this->uri->segment(4));
if ($this->input->post('name') !== FALSE) {
$data['name'] = $this->input->post('name');
} else {
$data['name'] = $user_group_info['name'];
}
$ignore = array(
'admin',
'login',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header',
'permission'
);
$data['controllers'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
if (!in_array($controller, $ignore)) {
$data['controllers'][] = $controller;
}
}
if ($this->input->post('name') !== FALSE) {
$data['controller'] = $this->input->post('controller');
} else {
$data['controller'] = $user_group_info['controller'];
}
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'User Group Name', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->load->view('template/user/users_group_form.tpl', $data);
} else {
$this->load->model('admin/user/model_user_group');
$this->model_user_group->addUserGroup($this->input->post());
redirect('admin/users_group');
}
}
}
?>
View
<?php echo validation_errors('<div class="alert alert-warning text-center"><i class="fa fa-exclamation-triangle"></i>
', '</div>'); ?>
<?php if ($this->uri->segment(4) == FALSE) { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'form-users-group');?>
<?php echo form_open('admin/users_group/add', $data);?>
<?php } else { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'form-users-group');?>
<?php echo form_open('admin/users_group/edit' .'/'. $this->uri->segment(4), $data);?>
<?php } ?>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('User Group Name', 'name', $data);?>
<div class="col-sm-10">
<?php $data1 = array('id' => 'name', 'name' => 'name', 'class' => 'form-control', 'value' => $name);?>
<?php echo form_input($data1);?>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Controller Name</td>
<td>Access</td>
<td>Modify</td>
</tr>
</thead>
<?php foreach ($controllers as $controller) {?>
<tbody>
<tr>
<td><?php echo $controller;?>
<input type="hidden" name="controller[]" value="<?php echo $controller;?>" />
</td>
<td>
<select name="access" class="form-control">
<option>1</option>
<option>0</option>
</select>
</td>
<td>
<select name="modify" class="form-control">
<option>1</option>
<option>0</option>
</select>
</td>
</tr>
</tbody>
<?php } ?>
</table>
<?php echo form_close();?>
The error is because you cannot insert php-array in database.
Instead store comma separated values.
In your model change data array as below:
public function addUserGroup($data) {
$controllers = $this->input->post('controller');
$name = $this->input->post('name');
$access = $this->input->post('access');
$modify = $this->input->post('modify');
for($i=0;$i<count($controllers);$i++) {
$data = array(
'name' => $name,
'controller' => $controllers[$i],
'access' => $access,
'modify' => $modify
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}
}
Your controller hidden field is an array. You're passing this array to your addUserGroup function, which is trying to insert this array into the database. It's implicitly trying to convert this array to a string. Maybe try changing your function to this:
'controller' => $this->input->post('controller')[0],
Problem fixed foreach in model Thanks for the ideas on how to fix problems every one.
foreach ($this->input->post('controller') as $controller) {
$data = array(
'name' => $this->input->post('name'),
'controller' => $controller,
'access' => $this->input->post('access'),
'modify' => $this->input->post('modify')
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}

Resources