File upload in codeigniter with other input field - php

I have studied the codeigniter documentation for file upload and implemented the file upload with only one file field, but now i have other input fields also , so i used the below code but there is DATABASE error "Column 'userfile' cannot be null", please tell me where i am wrong
view
<html>
<body>
<head>
<title>VALIDATION</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
<script>
$(document).ready(function(){
$("#sub").click(function(){
alert("Please check all required fields are filled.");
});
});
</script>
</head>
<form method="POST" action="<?php echo site_url('Dob_control/insert');?>" enctype="multipart/form-data">
<p>NAME:</p>
<?php echo form_error('name'); ?>
<input type="text" name="name" value="<?php echo set_value('name'); ?>" size="50">
<p>EMAIL:</p>
<?php echo form_error('email'); ?>
<input type="email" name="email" value="<?php echo set_value('email'); ?>" size="50">
<p>DATE:</p>
<?php echo form_error('date'); ?>
<input type="date" id="datepicker" name="date" value="<?php echo set_value('date'); ?>" size="50">
<p>NOTES:</p>
<?php echo form_error('notes'); ?>
<textarea name="notes" rows="4" cols="39"><?php echo set_value('notes'); ?></textarea>
<p>IMAGE:</p>
<input type="file" name="userfile" size="20" />
<br>
<input type="submit" id="sub" name="submit" value="submit">
</form>
</body>
</html>
model
<?php
class Dob_model extends CI_Model {
function __construct(){
parent::__construct();
$this->load->database();
}
function insert_record($student){
$this->db->insert('validate_table', $student); // insert data into `validate_table table`
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
}
?>
controller
<?php
class Dob_control extends CI_controller {
function __construct(){
parent::__construct();
$this->load->model('Dob_model');
}
function index(){
$this->load->helper(array('form','url'));
$this->load->view('simple_form');
}
public function insert(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('date','Date','required');
$this->form_validation->set_rules('notes','Notes','required', array( 'required' => 'Please complete this field'));
if ($this->form_validation->run() == FALSE)
{
$this->load->view('simple_form');
} else {
if ($this->input->post('submit') == true){
$student = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'date' => $this->input->post('date'),
'notes' => $this->input->post('notes'),
'userfile'=> $this->input->post('userfile'));
$result = $this->Dob_model->insert_record($student);
if($result==true){
echo "inserted";
}else
echo "Not Inserted";
} } }
public function do_upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000;
$config['max_width'] = 10244;
$config['max_height'] = 7685;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->Dob_control->display_errors());
$this->load->view('simple_form', $error);
} else {
$data = array('upload_data' => $this->Dob_control->data());
$this->load->view('upload_success', $data);
} } }
?>

First load the library.
$this->load->library('upload', $config);
Then upload your file
if ( $this->upload->do_upload('userfile'))
{
$data = array('upload_data' => $this->upload->data());
// $data will contain your file information
}
Please refer https://codeigniter.com/user_guide/libraries/file_uploading.html

Related

error in storing image in upload folder

My Controller Home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
//load database libray manually
$this->load->database();
//load Model
$this->load->model('Contact_model');
// load form and url helpers
$this->load->helper(array('form', 'url'));
// load form_validation library
$this->load->library('form_validation');
}
public function Latest_news()
{
$this->form_validation->set_rules('first_content', 'First content', 'required');
$this->form_validation->set_rules('second_content', 'Second content', 'required');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if (($this->form_validation->run() == FALSE )&&(!$this->upload->do_upload('filename')))
{
$this->load->view('Latest_news');
}
else
{
//insert
$data = array();
$data['first_content']=$this->input->post('first_content');
$data['second_content']=$this->input->post('second_content');
$data['filename']=$this->input->post('filename');
//Transfering data to Model
$this->Contact_model->latest_news($data);
//Redirecting to success page
redirect(site_url('Home/Latest_news'));
}
}
?>
My model Contact_model.php
<?php
class Contact_model extends CI_Model
{
function latest_news($data)
{
//saving records
$this->db->insert('latest_news', $data);
}
}
?>
Latest_news.php
<?php echo form_open(); ?>
<div style="padding-top:10%; padding-left:30%">
<div>
<textarea name="first_content" rows="4" cols="50"></textarea>
<span><?php echo form_error("first_content");?></span>
</div><br>
<div>
<textarea name="second_content" rows="4" cols="50"></textarea>
<span><?php echo form_error("second_content");?></span>
</div><br>
<div>
<input type="file" name="filename">
<span><?php echo form_error("filename");?></span>
</div><br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
Im trying to upload a image in database and store that image in one folder called upload, below is the code what i have tried with, the image name is getting stored in the database but its not getting stored in the folder, i don know where im going wrong please can any one look at my code and tel me
Hope this will help you :
Use FCPATH for the upload_path in your $config
Your Latest_news method should be like this :
public function Latest_news()
{
$this->form_validation->set_rules('first_content', 'First content', 'required');
$this->form_validation->set_rules('second_content', 'Second content', 'required');
if ($this->form_validation->run())
{
$config['upload_path'] = FCPATH.'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( $this->upload->do_upload('filename') )
{
print_r($this->upload->data());die;
$data['first_content'] = $this->input->post('first_content');
$data['second_content'] = $this->input->post('second_content');
$data['filename'] = $this->upload->data('file_name');
//Transfering data to Model
$this->Contact_model->latest_news($data);
//Redirecting to success page
redirect(site_url('Home/Latest_news'));
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);die;
}
}
else
{
$this->load->view('Latest_news');
}
}
Use form_open_multipart() instead of form_open()
Your form should be like this :
<?php echo form_open_multipart('Home/Latest_news'); ?>
<div style="padding-top:10%; padding-left:30%">
<div>
<textarea name="first_content" rows="4" cols="50"></textarea>
<span><?php echo form_error("first_content");?></span>
</div><br>
<div>
<textarea name="second_content" rows="4" cols="50"></textarea>
<span><?php echo form_error("second_content");?></span>
</div><br>
<div>
<input type="file" name="filename">
<span><?php echo form_error("filename");?></span>
</div><br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
For more : https://www.codeigniter.com/user_guide/libraries/file_uploading.html

how to check which button is clicked

this is my view i am submitted form using jquery,then I want to check which button is clicked either 'ADD PRODUCT' or SUBMIT button in controller
<?php echo form_open_multipart('itemcontroller/submit'); ?>
<div class="col-md-6">
<div class="add-name">
<label>Product Name</label>
<input type="text" id="product_name" name="product_name" placeholder="Product name">
<span id="pnerror" style="display: none;">Please enter Product Name</span>
</div>
<div class="add-name">
<label>Product Image</label>
<input type="file" id="user_file" name="user_file">
<span id="imgerror" style="display: none;">Please select an Image</span>
</div>
<div class="add-name">
<label>Product Category</label>
<?php $attributes = 'id="cat"';
echo form_dropdown('cat', $cat, set_value('cat'), $attributes); ?>
<span id="caterror" style="display: none;">Please select Category</span>
</div>
</div>
<div class="col-md-6">
<div class="add-name">
</div>
<div class="add-name">
<label>Product Description</label>
<textarea class="form-control" rows="8" id="product_description" name="product_description" placeholder="Product Description"></textarea>
<span id="pderror" style="display: none;">Please enter Product Description</span>
</div>
</div>
<div class="sub-add">
<button type="submit" form="form1" id="fill" name="fill" value="add">ADD PRODUCT</button>
</div>
<div class="sub-add">
<button type="submit" id="go" name="go" form="form1" value="go">SUBMIT</button>
</div>
<?php echo form_close(); ?>
this is my jquery code for ADD PRODUCT button.
<script type="text/javascript">
$('#fill').click(function(event){
var product_name = $('#product_name').val();
var image = $('#user_file').val();
var cat = $('#cat').val();
var product_description = $('#product_description').val();
if(product_name.length == 0)
{
$('#pnerror').show();
}
if(image.length == 0)
{
$('#imgerror').show();
}
if(cat == 0)
{
$('#caterror').show();
}
if(product_description.length == 0)
{
$('#pderror').show();
}
else if(product_name.length != 0 && image.length != 0 && cat != 0 && product_description.length != 0)
{
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
this is my SUBMIT button
<script type="text/javascript">
$('#go').click(function(event){
var product_name = $('#product_name').val();
var user_file = $('#user_file').val();
var cat = $('#cat').val();
var product_description = $('#product_description').val();
if(product_name.length == 0)
{
$('#pnerror').show();
}
if(user_file.length == 0)
{
$('#imgerror').show();
}
if(cat == 0)
{
$('#caterror').show();
}
if(product_description.length == 0)
{
$('#pderror').show();
}
else if(product_name.length != 0 && user_file.length != 0 && cat != 0 && product_description.length != 0)
{
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
This is my controller code:
public function submit()
{
print_r($_POST);
if($this->input->post('go'))
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 2048;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('user_file'))
{
$data = array('prod_data' => $this->upload->data());
$user_file = $data['prod_data']['raw_name']."".$data['prod_data']['file_ext'];
$id = $this->session->userdata['record']['id'];
$com_id = $this->session->userdata['record']['com_id'];
$sam = array(
'title' => $this->input->post('product_name'),
'type' => 'product'
);
$this->load->model('registermodel');
$chk = $this->registermodel->insertsam($sam);
if ($chk == TRUE)
{
$id = $this->registermodel->getsampleid();
$data = array(
'product_name' => $this->input->post('product_name'),
'image' => 'images/'.$user_file,
'product_description' => $this->input->post('product_description'),
'cat_id' => $this->input->post('cat'),
'com_id' => $com_id,
'id' => $id
);
$check = $this->registermodel->insertproduct($data);
if($check == TRUE)
{
echo "<script>
alert('Data Submitted Succesfully');
</script>";
redirect('/homecontroller');
}
else
{
echo "Value insertion Failed";
}
}
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
else if($this->input->post('fill'))
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 2048;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('user_file'))
{
$data = array('prod_data' => $this->upload->data());
$user_file = $data['prod_data']['raw_name']."".$data['prod_data']['file_ext'];
$id = $this->session->userdata['record']['id'];
$com_id = $this->session->userdata['record']['com_id'];
$sam = array(
'title' => $this->input->post('product_name'),
'type' => 'product'
);
$this->load->model('registermodel');
$chk = $this->registermodel->insertsam($sam);
if ($chk == TRUE)
{
$id = $this->registermodel->getsampleid();
$data = array(
'product_name' => $this->input->post('product_name'),
'image' => 'images/'.$user_file,
'product_description' => $this->input->post('product_description'),
'cat_id' => $this->input->post('cat'),
'com_id' => $com_id,
'id' => $id
);
$check = $this->registermodel->insertproduct($data);
if($check == TRUE)
{
echo "<script>
alert('Product added Succesfully');
</script>";
$data['category'] = $this->linkmodel->get_category();
$data['cat'] = $this->registermodel->get_category();
$this->load->view('itemview',$data);
}
else
{
echo "Value insertion Failed";
}
}
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
}
print_r($_POST);
this returns only this :
Array ( [product_name] => Multifunction Printer Machine [cat] => 82 [product_description] => Approx Price: Rs 80,000 / Piece)
not return ADD PRODUCT OR SUBMIT button name, please anyone tell me what i am doing wrong ?
You may have to use <input type="submit" ...> instead of <button ...>. It should append buttons' name and value to $_POST.
Add input hidden field in your form and set different value in each JavaScript code.
<?php echo form_open_multipart('itemcontroller/submit'); ?>
<!-- your existing code --->
<input type="hidden" name="submit_type" id="submit_type" value="" />
<?php echo form_close(); ?>
JavaScript code Modification
<script type="text/javascript">
$('#go').click(function(event){
<!-- your existing code --->
$('#submit_type').val('SUBMIT');
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
<script type="text/javascript">
$('#fill').click(function(event){
<!-- your existing code --->
$('#submit_type').val('ADD PRODUCT');
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>

adding login functionality to my project in codeigniter

I have registeration form which redirects to listing page. Now i want to add login functionality to my page and after login my page should show respective users form autofilled. But i didnt get how to use it please help.
controller
function login(){
$this->load->view('login_form.php');
}
function check_login(){
if($_POST) {
$result = $this->Student_info_model->validate_user($_POST);
if(!empty($result)) {
$data = ['id' => $result->user,'name' => $result->name ];
$this->session->set_userdata($data);
redirect('home');
} else {
$this->session->set_flashdata('flash_data', 'Username or password is wrong!');
redirect('Student_info/login');
}
}
Model
public function validate_user($data) {
$this->load->database();
$this->db->where('name', $data['name']);
$this->db->where('password', md5($data['password']));
return $this->db->get('student_info_table')->row();
}
View
<html>
<body>
<form action="<?php echo site_url('Student_info/check_login');?>"method="post">
<label for="username">Username</label>
<input type="text" name="username" /><br>
<label for="password">password</label>
<input type="text" name="password" /><br>
<input type="submit" value="login"/>
</form>
Try this one
The Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->model('login_model');
}
public function index()
{
if(($this->session->userdata('logged_in')==1) && ($this->session->userdata('role')==1))
{
redirect(base_url('admin/dashboard'),'refresh');
}
if(($this->session->userdata('logged_in')==1) && ($this->session->userdata('role')==2))
{
redirect(base_url('teacher/dashboard'),'refresh');
}
if(($this->session->userdata('logged_in')==1) && ($this->session->userdata('role')==2))
{
redirect(base_url('student/dashboard'),'refresh');
}
$data['title']='User Login';
$this->load->view('login',$data);
}
public function login_action()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric');
$this->form_validation->set_rules('userpassword', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('user-error', 'Username or password are incorrect !');
redirect(base_url().'user');
}
else
{
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('userpassword')
);
$result =$this->login_model->userlogin($data);
if ($result == TRUE)
{
$username = $this->input->post('username');
$result = $this->login_model->get_userinfo($username);
if ($result != false) {
$session_data = array(
'userid' => $result[0]->userid,
'username' => $result[0]->username,
'email' => $result[0]->email,
'role'=>$result[0]->role,
'logged_in'=>1
);
$role=$result[0]->role;
$this->session->set_userdata($session_data);
if($role=='1')
{
redirect(base_url().'admin/dashboard');
}
if($role=='2')
{
$this->load->view('teacher');
}
if($role=='3')
{
$this->load->view('student');
}
}
}
else
{
$this->session->set_flashdata('user-error', 'Username or password are incorrect!');
redirect(base_url().'user');
}
}
}
public function logout()
{
$this->session->sess_destroy();
$this->session->set_flashdata('user-out','You have been logout Successfully');
redirect(base_url().'user');
}
}
The Model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class login_model extends CI_Model
{
public function __contruct()
{
parent::__construct();
$this->load->database();
}
public function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1)
{
return true;
}
else
{
return false;
}
}
public function get_userinfo($username)
{
$condition = "username =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
The View
<!DOCTYPE HTML>
<html>
<head>
<title><?php echo $title ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<link href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" rel='stylesheet' type='text/css' />
<link href="<?php echo base_url(); ?>assets/css/style.css" rel='stylesheet' type='text/css' />
<link href="<?php echo base_url(); ?>assets/css/font-awesome.css" rel="stylesheet">
<script src="<?php echo base_url(); ?>assets/js/jquery.min.js"></script>
<!----webfonts--->
<link href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900' rel='stylesheet' type='text/css'>
<!---//webfonts--->
<!-- Bootstrap Core JavaScript -->
<script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script>
</head>
<body id="login">
<div class="login-logo">
<img src="<?php echo base_url(); ?>assets/images/logo.png" alt=""/>
</div>
<h2 class="form-heading">login</h2>
<div class="app-cam">
<?php
if($this->session->flashdata('user-out')) { echo '<p class="text-success">'.$this->session->flashdata('user-out').'</p>';}
if($this->session->flashdata('user-error')) { echo '<p class="text-danger">'.$this->session->flashdata('user-error').'</p>';} ?>
<form action="<?php echo base_url(),'user/login_action'; ?>" method="post">
<input type="text" name="username" class="text" value="E-mail address" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'E-mail address';}">
<input type="password" name="userpassword" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}">
<div class="submit"><input type="submit" onclick="myFunction()" value="Login"></div>
<div class="login-social-link">
<a href="" class="facebook">
Facebook
</a>
<a href="" class="twitter">
Twitter
</a>
</div>
<ul class="new">
<li class="new_left"><p>Forgot Password ?</p></li>
<li class="new_right"><p class="sign">New here ? Sign Up</p></li>
<div class="clearfix"></div>
</ul>
</form>
</div>
<div class="copy_layout login">
<p>Copyright © 2015 Modern. All Rights Reserved | Design by W3layouts </p>
</div>
</body>
</html>

My picture is not saved into my uploads/pictures folder

My Controller Codes
Looking forward for your help! thank you :
public function index()
{
$registration = $this->Registration_model->get_all();
$data = array(
'registration_data' => $registration
);
$this->load->view('registration/registration_list', $data);
}
public function do_upload()
{
$config['upload_path'] = './uploads/pictures/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000000;
$config['max_width'] = 10240000;
$config['max_height'] = 76800000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('Image'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('registration_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data['upload_data']['file_name'];
}
}
public function read($id)
{
$row = $this->Registration_model->get_by_id($id);
if ($row) {
$data = array(
'id' => $row->id,
'firstName' => $row->firstName,
'lastName' => $row->lastName,
'gender' => $row->gender,
'address' => $row->address,
'dob' => $row->dob,
'Image' => $row->Image,
);
$this->load->view('registration/registration_read', $data);
} else {
$this->session->set_flashdata('message', 'Record Not Found');
redirect(site_url('registration'));
}
}
public function create()
{
$data = array(
'button' => 'Create',
'action' => site_url('registration/create_action'),
'id' => set_value('id'),
'firstName' => set_value('firstName'),
'lastName' => set_value('lastName'),
'gender' => set_value('gender'),
'address' => set_value('address'),
'dob' => set_value('dob'),
'Image' =>set_value('image'),
);
$this->load->view('registration/registration_form', $data);
}
public function create_action()
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data = array(
'firstName' => $this->input->post('firstName',TRUE),
'lastName' => $this->input->post('lastName',TRUE),
'gender' => $this->input->post('gender',TRUE),
'address' => $this->input->post('address',TRUE),
'dob' => $this->input->post('dob',TRUE),
'Image' => $this->input->post('Image',TRUE),
);
$this->Registration_model->insert($data);
$this->session->set_flashdata('message', 'The New Record was Successfuly Added');
redirect(site_url('registration'));
}
}
My Views Codes
<div class="form-group">
<label for="date">Dob <?php echo form_error('dob') ?></label>
<input type="text" class="form-control" name="dob" id="dob" placeholder="Dob" value="<?php echo $dob; ?>" />
</div>
<div class="form-group">
<label for="varchar">Image <?php echo form_open_multipart('upload/do_upload');?></label>
<input type="file" class="form-control" name="Image" id="Image" height="50" />
<br/>
</div>
<br/>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<button type="submit" class="btn btn-primary"name="userSubmit"><?php echo $button ?></button>
My Model
class Registration_model extends CI_Model
{
public $table = 'registration';
public $id = 'id';
public $order = 'DESC';
function __construct()
{
parent::__construct();
}
// get all
function get_all()
{
$this->db->order_by($this->id, $this->order);
return $this->db->get($this->table)->result();
}
// get data by id
function get_by_id($id)
{
$this->db->where($this->id, $id);
return $this->db->get($this->table)->row();
}
// get total rows
function total_rows($q = NULL) {
$this->db->like('id', $q);
$this->db->or_like('firstName', $q);
$this->db->or_like('lastName', $q);
$this->db->or_like('gender', $q);
$this->db->or_like('address', $q);
$this->db->or_like('dob', $q);
$this->db->or_like('Image', $q);
$this->db->from($this->table);
return $this->db->count_all_results();
}
// get data with limit and search
function get_limit_data($limit, $start = 0, $q = NULL) {
$this->db->order_by($this->id, $this->order);
$this->db->like('id', $q);
$this->db->or_like('firstName', $q);
$this->db->or_like('lastName', $q);
$this->db->or_like('gender', $q);
$this->db->or_like('address', $q);
$this->db->or_like('dob', $q);
$this->db->or_like('Image', $q);
$this->db->limit($limit, $start);
return $this->db->get($this->table)->result();
}
// insert data
function insert($data)
{
$this->db->insert($this->table, $data);
}
// update data
function update($id, $data)
{
$this->db->where($this->id, $id);
$this->db->update($this->table, $data);
}
// delete data
function delete($id)
{
$this->db->where($this->id, $id);
$this->db->delete($this->table);
}
}
Hello You can try this
$config['upload_path'] = 'ADD HERE YOUR SITE PATH TO PICTURE'; // Like SITE_PATH .'/uploads/pictures/';
and print $config['upload_path'] and check it's correct your upload picture path
I've had the same issue before. Depending on your server, you may want to remove the ./ from your upload path.
public function do_upload()
{
$config['upload_path'] = 'uploads/pictures/';
Change your view as below. You are not closing form
<?php echo form_open_multipart('upload/do_upload');?>
<div class="form-group">
<label for="date">Dob <?php echo form_error('dob') ?></label>
input type="text" class="form-control" name="dob" id="dob" placeholder="Dob" value="<?php echo $dob; ?>" />
</div>
<div class="form-group">
<label for="varchar">Image </label>
<input type="file" class="form-control" name="Image" id="Image" height="50" />
<br/>
</div>
<br/>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<button type="submit" class="btn btn-primary"name="userSubmit"><?php echo $button ?></button>
<?= form_close()?>

Registration form with image upload in Codeigniter

I have a user registration form and it's working fine but would like to add an image upload feature inside it. This is basically what I'd like to achieve
ScreenShot 1
ScreenShot 2
So far, this is what I have done
Controller:
class Employees extends CI_Controller {
var $pgToLoad;
public function __construct() {
parent::__construct();
#this will start the session
session_start();
$this->load->helper(array('form', 'url'));
if(!isset($_SESSION['userId']) || !isset($_SESSION['userLevel']) || !isset($_SESSION['employeeid']) || !isset($_SESSION['firstname']) || !isset($_SESSION['lastname'])) {
redirect('home', 'location');
}
#this will load the model
$this->load->model('Contents');
#get last uri segment to determine which content to load
$continue = true;
$i = 0;
do {
$i++;
if ($this->uri->segment($i) != "") $this->pgToLoad = $this->uri->segment($i);
else $continue = false;
} while ($continue);
}
public function index() {
$this->main();
}
public function main() {
#set default content to load
$this->pgToLoad = empty($this->pgToLoad) ? "employees" : $this->pgToLoad;
$disMsg = "";
#this will delete the record selected
if($this->uri->segment(2) == 'delete') {
$this->deleteRecord();
}
#this will check if the post value is trigger
if(isset($_POST['addnew'])) {
$this->addRecord();
}
#this will check if the post value is trigger
if(isset($_POST['saveinfo'])) {
$this->updateinfo();
}
if($this->uri->segment(2) == 'add' || $this->uri->segment(2) == 'edit') {
#this display the form for products
$this->displayForm();
} else {
#this will display the job orders
$this->getAllEmployees();
}
if($this->uri->segment(2) == 'print') {
#this display the form for products
$this->pdf();
}
if($this->uri->segment(2) == 'do_upload') {
#this display the form for products
$this->do_upload();
}
#this will logout the user and redirect to the page
if($this->uri->segment(2) == 'logout') {
session_destroy();
redirect('home', 'location');
}
$data = array ( 'pageTitle' => 'Payroll System | ADMINISTRATION',
'disMsg' => $disMsg,
'mainCont' => $this->mainCont );
$this->load->view('mainTpl', $data, FALSE);
}
function do_upload(){
if($this->input->post('upload')){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('pages/employeesform', $error);
}
else{
$data=$this->upload->data();
$this->thumb($data);
$file=array(
'img_name'=>$data['raw_name'],
'thumb_name'=>$data['raw_name'].'_thumb',
'ext'=>$data['file_ext'],
'upload_date'=>time()
);
$this->Contents->add_image($file);
$data = array('upload_data' => $this->upload->data());
$this->load->view('pages/upload_success', $data);
}
}
else{
redirect(site_url('employees'));
}
}
function thumb($data){
$config['image_library'] = 'gd2';
$config['source_image'] =$data['full_path'];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 275;
$config['height'] = 250;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
public function displayForm() {
$data['level'] = $this->Contents->exeGetUserLevel();
$data['status'] = $this->Contents->exeGetUserStatus();
$data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
if($this->uri->segment(2) == 'edit') {
$data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
$data['emp'] = $this->Contents->exeGetEmpToEdit($this->uri->segment(3));
$data['info'] = $this->Contents->exeGetUserInfo($this->uri->segment(3));
$this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
}
$this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
}
#this will add new record
public function addRecord() {
if(empty($_POST['fname']) || empty($_POST['mname']) || empty($_POST['lname']) || empty($_POST['empass']) || empty($_POST['emailadd']) || empty($_POST['gender']) || empty($_POST['datehired']) || empty($_POST['salary'])) {
$disMsg = "Please fill up the form completely.";
$_SESSION['disMsg'] = $disMsg;
} else {
$addNew = $this->Contents->exeAddNewRecord();
if($addNew['affRows'] > 0) {
$_SESSION['disMsg'] = "New Employee has been added.";
redirect('employees', 'location');
} else {
$disMsg = "Unable to add new employee.";
}
}
}
Views:
<?php echo form_open_multipart('employees/do_upload');?>
<img id="preview" style = "width: 200px; height: 200px;">
<input type="file" name = "userfile" id="input">
<br /><br />
<input type="submit" value="upload" name="upload" />
</form>
<form action="" method="post" enctype="multipart/form-data" id="empform" role="form" name="empform">
<div class="box-body">
<div class="row">
<div class="col-lg-6">
<div class="input-field col s12">
<label>Firstname</label>
<input type="text" id="fname" name="fname" class="form-control" value="<?php if(!empty($_POST['fname'])) { echo $_POST['fname']; } elseif(!empty($emp[0]['firstname'])) { echo $emp[0]['firstname']; } ?>">
</div>
<div class="input-field col s12">
<label>Middle Name</label>
<input type="text" id="mname" name="mname" class="form-control" value="<?php if(!empty($_POST['mname'])) { echo $_POST['mname']; } elseif(!empty($emp[0]['middlename'])) { echo $emp[0]['middlename']; } ?>">
</div>
<div class="input-field col s12">
<label>Password</label>
<input type="password" id="empass" name="empass" class="form-control" value="<?php if(!empty($_POST['empass'])) { echo $_POST['empass']; } ?>">
</div>
<div class="input-field col s12">
<label>Employee ID</label>
<input type="text" id="empno" name="empno" class="form-control" value="<?php if(!empty($_POST['empno'])) { echo $_POST['empno']; } elseif(!empty($emp[0]['employeeid'])) { echo $emp[0]['employeeid']; } ?>">
</div>
</div>
<div class="col-lg-4" style="padding-left:0;">
<?php if($this->uri->segment(2) == "edit") { ?>
<button type="submit" name="saveinfo" class="btn btn-lg btn-primary btn-block">Save</button>
<?php } else { ?>
<button type="submit" name="addnew" class="btn btn-lg btn-primary btn-block">Save</button>
<?php } ?>
</div>
</div>
</div>
</form>
As you can see in views, there are 2 forms. First form is for image upload and the other one is user registration form. How will I be able to include the image upload in the reg form and perform image upload, save user info and form validation once save button is clicked?
This is how I handle file uploads with form... it's a generic example but it should help.
View
<?php echo form_open_multipart('someController/someFunction') ?>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name">
</div>
<div class="form-group">
<label for="uploads">Upload a file</label>
<input name="uploads[]" id="fileupload" type="file" multiple="true">
</div>
<input type="submit">
<?php echo form_close() ?>
Controller
public function addRecordToTable()
{
$this->form_validation->set_rules('name' , 'Name', 'required');
if ($this->form_validation->run() == true) {
$array = array(
'name' => $this->input->post('name')
);
$record_id = $this->some_model->addData('some_table', $array);
$this->uploadFiles($record_id);
}
}
public function uploadFiles($record_id)
{
$config = array(
'upload_path' => FCPATH . "path\to\directory",
'allowed_types' => 'jpg|png|jpeg',
'overwrite' => TRUE,
);
$this->load->library('upload', $config);
$files = $_FILES['uploads'];
foreach ($files['name'] as $key => $filename) {
$_FILES['uploads[]']['name'] = $files['name'][$key];
$_FILES['uploads[]']['type'] = $files['type'][$key];
$_FILES['uploads[]']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['uploads[]']['error'] = $files['error'][$key];
$_FILES['uploads[]']['size'] = $files['size'][$key];
$config['file_name'] = $filename;
$this->upload->initialize($config);
if (isset($_FILES['uploads[]']['name']) && !empty($_FILES['uploads[]']['name'])) {
if ( ! $this->upload->do_upload('uploads[]')) {
$error = array('error' => $this->upload->display_errors());
} else {
$uploads[] = $this->upload->data();
$array = array(
'record_id' => $record_id,
'filename' => $_FILES['uploads[]']['name'],
'size' => $_FILES['uploads[]']['size']
);
$this->some_model->addData('uploads', $array);
}
}
}
redirect(base_url() . 'someController/someFunction/' . $record_id);
}
Model
public function addData($table, $array)
{
$this->db->insert($table, $array);
return $this->db->insert_id();
}
Edit:
As per your comment, to insert data into multiple tables, simply modify the code in your controller so:
public function submitEmployeeDetails()
{
$this->form_validation->set_rules('value1' , 'Value 1', 'required');
$this->form_validation->set_rules('value2' , 'Value 2', 'required');
if ($this->form_validation->run() == true) {
$array1 = array(
'value1' => $this->input->post('value1')
);
$array2 = array(
'value2' => $this->input->post('value2')
);
$this->your_model->addData('employees', $array1);
$this->your_model->addData('employees_details', $array2);
}
}
So you have two arrays and you call the addData() function in the model, the first parameter specifies the name of the table and the second passes the associative array to be added.

Categories