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.
Related
Actually, I have saved all the data in database after i have show in front end,in my side issue is i have created upload image function to save database after i fetch and display the front end,upload function is taking to save full path like :C:/xampp/www/htdocs/rentozy/admin/images/media/rajkumar-1515559187/1.jpg. all the images saved folder also but in front end is coming like this only : C:/xampp/www/htdocs/rentozy/admin/images/media/rajkumar-1515559187/1.jpg please i need save database like this : (images/media/rajkumar-1499778784/19510.jpg) please help me how will resolve this this is my first sit is codeigniter please help how will pass like this url.
Here my code for controller:
function addNewMedia()
{
if($this->isAdmin() == TRUE)
{
$this->loadThis();
}
else
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Name','trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('event_image','Pg Image');
// $this->form_validation->set_rules('media_image','Image');
// $this->form_validation->set_rules('date_added','Date','trim|required');
if($this->form_validation->run() == FALSE)
{
$this->addNew();
}
else
{
$data = array(); $upload_data = array();
$this->load->library('upload');
$data['name'] = $this->input->post('name');
$folder_srting = $data['name']."-".time();
$data['name'] = $this->input->post('name');
// print_r($folder_srting);
$folder_string = str_replace(' ', '-', $folder_srting);// Replaces all spaces with hyphens.
$folder_string = preg_replace('/[^A-Za-z0-9\-]/', '', $folder_srting);// Removes special chars.
$folder_name = preg_replace('/-+/', '-', strtolower($folder_string));// Replaces multiple hyphens with single one.
print_r($folder_name);
//$data['name'] = $this->input->post('name');
//$pg_id = $this->input->post('pg_id');
if ($_FILES['event_image']['error'] != 4)
{
$folder = $this->checkdirectory($folder_name);
//print_r($folder_name);
$this->upload->initialize($this->set_upload_options($folder));
if ( ! $this->upload->do_upload('event_image'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error); die;
}
else
{
$upload_data['banner_data'] = $this->upload->data();
//print_r($upload_data['banner_data']);die;
$upload_data['bannerfilepath'] = $upload_data['banner_data']['full_path'];
//print_r($upload_data['bannerfilepath']);die;
}
foreach($upload_data['banner_data'] as $bannerfilepath){
$data['banner_image_path'] = str_ireplace(FCPATH,"", $upload_data['banner_data']['full_path']);
//print_r($data['banner_image_path']);die;
}
$event_image = $data['banner_image_path'];
//print_r($event_image);die;
}
// $name = ucwords(strtolower($this->input->post('name')));
$event_image = $event_image;
//print_r($event_image);die;
$name = $this->input->post('name');
$address = $this->input->post('pg_address');
$incharge_name = $this->input->post('pg_incharge_name');
$incharge_mobile = $this->input->post('pg_incharge_mobile');
$email = $this->input->post('pg_email');
$mediaInfo = array('name'=>$name,'event_image'=>$event_image,'pg_address'=>$address,'pg_incharge_name'=>$incharge_name,'pg_incharge_mobile'=> $incharge_mobile,'pg_email'=>$email,'folder_name'=>$folder);
//echo "<pre>";print_r($mediaInfo);die;
$this->load->model('media_model');
//echo "<pre>";print_r($mediaInfo);die;
$result = $this->media_model->addNewMedia($mediaInfo);
if($result > 0)
{
$this->session->set_flashdata('success', 'New Pg created successfully');
}
else
{
$this->session->set_flashdata('error', 'Pg creation failed');
}
redirect('mediaListing');
}
}
}
function editMedia()
{
if($this->isAdmin() == TRUE)
{
$this->loadThis();
}
else
{
$this->load->library('form_validation');
$eventId = $this->input->post('pg_id');
$this->form_validation->set_rules('name','Name','trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('event_image','Pg Image');
//$this->form_validation->set_rules('event_description','Event Description','required|max_length[200]');
// $this->form_validation->set_rules('start_date','Start Date','trim|required');
//$this->form_validation->set_rules('end_date','End Date','trim|required');
//$this->form_validation->set_rules('additional_images','Additional Images');
//$this->form_validation->set_rules('short_description','Short Description','required');
if($this->form_validation->run() == FALSE)
{
$this->editNew($eventId);
}
else
{
$data = array(); $upload_data = array();
$this->load->library('upload');
$existing_folder = $_POST['folder_name'];
//print_r($existing_folder);die;
if(isset($_POST['image_exists']) && $_POST['image_exists']!= '')
$temp_attachment = $_POST['image_exists'];
$folder = $this->checkdirectory($existing_folder);
if (isset($_FILES['event_image']['name']) && $_FILES['event_image']['error'][0] != 4 && $_FILES['event_image']['name']!='') {
$this->upload->initialize($this->set_upload_options($folder));
if ( ! $this->upload->do_upload('event_image'))
{
$error = array('error' => $this->upload->display_errors());
//print_r($error); die;
}
else
{
$upload_data['banner_data'] = $this->upload->data();
$upload_data['bannerfilepath'] = $upload_data['banner_data']['full_path'];
}
// GET REQUIRED BANNER IMAGES FILE PATH FROM FULL PATH
foreach($upload_data['banner_data'] as $bannerfilepath){
$data['banner_image_path'] = str_ireplace(FCPATH,"", $upload_data['banner_data']['full_path']);
print_r($data['banner_image_path']);die;
}
$event_image = $data['banner_image_path'];
//print_r($event_image);die;
}
else{
// echo "sfgjdf";
$event_image = $temp_attachment;
// print_r($event_image);die;
}
$event_image = $event_image;
$name = $this->input->post('name');
$pg_address = $this->input->post('pg_address');
$pg_incharge_name = $this->input->post('pg_incharge_name');
$pg_incharge_mobile = $this->input->post('pg_incharge_mobile');
$pg_email = $this->input->post('pg_email');
// $additional_images = $additional_images;
$mediaInfo = array('name'=>$name,'event_image'=>$event_image,'pg_address'=>$pg_address,'pg_incharge_name'=>$pg_incharge_name,'pg_incharge_mobile'=>$pg_incharge_mobile,'pg_email'=>$pg_email,'folder_name'=>$folder);
//echo "<pre>";print_r($mediaInfo);die;
$result = $this->media_model->editMedia($mediaInfo, $eventId);
if($result == true)
{
$this->session->set_flashdata('success', 'Pg updated successfully');
}
else
{
$this->session->set_flashdata('error', 'Pg updation failed');
}
redirect('mediaListing');
}
}
}
here my model:
function addNewMedia($mediaInfo)
{
$this->db->trans_start();
$this->db->insert('tbl_master_property', $mediaInfo);
$insert_id = $this->db->insert_id();
$this->db->trans_complete();
return $insert_id;
}
function getMediaInfo($eventId)
{
$this->db->select('pg_id, name,event_image,pg_address,pg_incharge_name,pg_incharge_mobile,pg_email,folder_name');
$this->db->from('tbl_master_property');
$this->db->where('status', 0);
$this->db->where('pg_id', $eventId);
$query = $this->db->get();
return $query->result();
}
function editMedia($mediaInfo, $eventId)
{
$this->db->where('pg_id', $eventId);
$this->db->update('tbl_master_property', $mediaInfo);
return TRUE;
}
here my view file code:
<?php
define("IMAGE_PATH", "http://localhost/rentozy/admin/");
$eventId = '';
$name = '';
$pg_address = '';
$pg_incharge_name = '';
$pg_incharge_mobile = '';
$pg_email ='';
$event_image = '';
$folder_name = '';
if(!empty($mediaInfo))
{
foreach ($mediaInfo as $ef)
{
$eventId = $ef->pg_id;
$name = $ef->name;
$pg_address = $ef->pg_address;
$pg_incharge_name = $ef->pg_incharge_name;
$pg_incharge_mobile = $ef->pg_incharge_mobile;
$pg_email = $ef->pg_email;
$event_image = $ef->event_image;
$folder_name = $ef->folder_name;
}
}
?>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script> <script type="text/javascript">
//<![CDATA[
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
//]]>
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<i class="fa fa-users"></i> Property Management
<small>Add / Edit Property</small>
</h1>
</section>
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Enter Property Details</h3>
</div><!-- /.box-header -->
<!-- form start -->
<form role="form" action="<?php echo base_url() ?>editMedia" method="post" id="editEvent" role="form" enctype="multipart/form-data" files="true">
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="event_name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name" value="<?php echo $name; ?>" maxlength="128" readonly>
<input type="hidden" value="<?php echo $eventId; ?>" name="pg_id" id="eventId" />
<input type="hidden" value="<?php echo $folder_name; ?>" name="folder_name"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6" style="padding-bottom:15px;">
<div class="form-group">
<label for="description" class="pull-left">Pg Address</label>
<textarea rows="6" cols="50" name="pg_address" class="pull-left" style="width:100%;" value="<?php echo $pg_address;?>" id="pgaddress"><?php echo $pg_address;?></textarea>
</div>
</div>
<div class="col-md-6" style="padding-bottom:15px;">
<div class="form-group">
<label for="description" class="pull-left">Pg Incharge Name</label>
<div class="clearfix"></div>
<textarea rows="6" cols="50" name="pg_incharge_name" class="pull-left" style="width:100%;" value="<?php echo $pg_incharge_name;?>" id="pg_incharge_name" ><?php echo $pg_incharge_name;?></textarea>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="start-date">Pg Incharge Mobile</label>
<input type="text" class="form-control required pg_incharge_mobile" value="<?php echo $pg_incharge_mobile;?>" id="pg_incharge_mobile" name="pg_incharge_mobile">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="end-date">Pg Email</label>
<input type="text" class="form-control pg_email" value="<?php echo $pg_email;?>" id="pg_email" name="pg_email">
</div>
<div class="col-md-6">
<div class="col-md-6">
<div class="form-group">
<label for="event_image">Pg Image</label>
<input type="file" value="<?php echo $event_image; ?>" class="form-control file_change1" id="eventimage" name="event_image">
<img src="<?php echo IMAGE_PATH.$event_image;?>" width="100px" height="50px">
<input type="hidden" name="image_exists" value="<?php echo $event_image;?>" class="form-control" id="eventimage" placeholder="Enter Image Text" aria-describedby="fileHelp">
<div><?php echo $event_image;?></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I don't know if you've thought about it, but you could easily use PHP's str_replace to do what you need.
<?php
$path = $upload_data['banner_data']['full_path'];
$dir = 'C:/xampp/www/htdocs/rentozy/admin/';
$url = str_replace( $dir, '', $path );
echo $url;
In CodeIgniter, if you are saving to a path that is a directory off of document root, you can use the FCPATH constant to make this easy. So if your path to your upload folder is in a directory named /uploads/, and /uploads/ is at document root, then:
<?php
$path = $upload_data['banner_data']['full_path'];
$dir = FCPATH . 'uploads/';
$url = str_replace( $dir, '', $path );
echo $url;
This is just an example, but it is easy
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>
I have this edit page that has gets its id and status from uri segments. The problem is that if the user doesn't select an image or complete a part of the form, the page is supposed to reload and show the validation errors for the form. However that page reload causes the data in the form to go missing. Is there a way to solve this issue? Any help would be greatly appreciated. I attached my view, and controller
View
<?php if($edit == "false"){
echo form_open_multipart('Control/Products/ProductDetail/addProduct','class="productdetail"');
}else{
echo form_open_multipart('Control/Products/ProductDetail/editProduct','class="productdetail"');
}?>
<label for="inputproductname">Product Name</label>
<input type="text" class="form-control" id="inputproductname" name="inputproductname" placeholder="Name" value="<?php echo $name; ?>">
<label for="inputproductdescription">Product Description</label>
<textarea class="form-control" id="inputproductdescription" name="inputproductdescription" placeholder="Description" rows="7"
><?php echo $description; ?></textarea>
<label for="inputproductprice">Product Price</label>
<input type="price" class="form-control" id="inputproductprice" name="inputproductprice" placeholder="Price" value="<?php echo $price; ?>">
<label for="inputproductimage">Product Image</label>
<p><input type="file" class="form-control-file" name="upload" id="upload" aria-describedby="fileHelp"></p>
<input type="hidden" class="form-control" id="inputcurrentid" name="inputcurrentid" value="<?php echo $currentid; ?>">
<input type="hidden" class="form-control" id="inputcurrentstatus" name="inputcurrentstatus" value="<?php echo $currentstatus; ?>">
<button type="submit" class="btn btn-primary">
<?php if($edit == "false"){
echo "Add";
}else{
echo "Edit";
}?>
</button>
Cancel
<?php echo form_close(); ?>
<?php echo validation_errors(); ?>
<p><?php echo $this->session->flashdata('Form'); ?></p>
Controller
public function index(){
$productid = $this->uri->segment(5);
$editstatus = $this->uri->segment(6);
if($editstatus == "false"){
$data['name'] = '';
$data['description'] = '';
$data['price'] = '';
$data['edit'] = "false";
$data['message']='';
$data['currentid'] = '';
$data['currentstatus'] = '';
}else{
$product = $this->ProductsModel->getProduct($productid);
foreach ($product as $productdetail){
$data['name'] = $productdetail->name;
$data['description'] = $productdetail->description;
$data['price'] = $productdetail->price;
}
$data['edit'] = "true";
$data['message']='';
$data['currentid'] = $productid;
$data['currentstatus'] = $editstatus;
}
$this->load->view('control/controlMenu/navigationLink');
$this->load->view('control/controlProducts/productDetail',$data);
$this->load->view('control/controlMenu/navigationJquery');
}
public function editProduct(){
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
$this->form_validation->set_rules('inputproductname', 'Name', 'trim|required');
$this->form_validation->set_rules('inputproductdescription', 'Description', 'trim|required');
$this->form_validation->set_rules('inputproductprice', 'Price', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('upload', 'Image', 'required');
}
$inputproductname = $this->input->post('inputproductname');
$inputproductdescription = $this->input->post('inputproductdescription');
$inputproductprice = $this->input->post('inputproductprice');
$inputdateadded = date('Y-m-d');
$inputcurrentid = $this->input->post('inputcurrentid');
$inputcurrentstatus = $this->input->post('inputcurrentstatus');
$config['upload_path'] = $this->getProductImageFolderPath();
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = 3000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['file_name'] = $inputproductname;
$this->load->library('upload', $config);
if($this->form_validation->run()==false){
redirect('/Control/Products/ProductDetail/index/'.$inputcurrentid.'/'.$inputcurrentstatus);
}else{
if(!$this->upload->do_upload('upload')){
$this->session->set_flashdata('Form',$this->upload->display_errors());
redirect('Control/'.$this->getCurrentModule().'/'.$this->getClassName());
}else{
$extension = $this->upload->data('file_ext');
$productdetails = array(
'name'=>$inputproductname,
'description'=>$inputproductdescription,
'price'=>$inputproductprice,
'imagePath'=>$config['upload_path'].$config['file_name'].$extension,
'dateAdded'=>$inputdateadded
);
$this->db->trans_start();
$this->ProductsModel->editProduct($productid,$productdetails);
$this->db->trans_complete();
if($this->db->trans_status()===false){
}else{
$this->session->set_flashdata('Form', $inputproductname . ' has been altered on the database');
redirect('/Control/Products/Products');
}
}
}
}
if($this->form_validation->run()==false){
redirect('/Control/Products/ProductDetail/index/'.$inputcurrentid.'/'.$inputcurrentstatus);
I think the problem with this redirect stmt don't use it instead you need to use load view so that it will preserves the errors array.
just do ths in your controller
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('field', form_error('field', '<span class="text-danger pl-3">', '</span>'));
redirect("url");
} else {
# code...
}
and in your redirect page use
<?= $this->session->flashdata('field'); ?>
This is my view file where form for image and other data exists:
<?php echo form_open_multipart('Login/client_profile'); ?>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control" name="company_name" >
</div>
<div class="form-group">
<label>Upload Profile Picture</label>
<input type="file" name="profile_pic" accept="image/*" class="form-control" required>
</div>
<div class="form-group">
<label>Mobile Number</label>
<input type="number" class="form-control" name="mobile" required>
</div>
<div class="form-group">
<label>Specialist in</label>
<input type="text" class="form-control" name="specialist_in" >
</div>
<div class="form-group">
<label>Position</label>
<input type="text" class="form-control" name="position" >
</div>
<?php
$data7 = array(
'type' => 'submit',
'value' => 'Update',
'class' => 'btn btn-primary ',
);
echo form_submit($data7);
echo form_close();
?>
This is the controller file Client.php
public function client_profile()
{
$client=$this->input->post();
$client['profile_pic']=$this->input->post('profile_pic');
$this->load->model('Clientmodel');
$email=$this->session->userdata('email_id');
$this->Clientmodel->add_client_details($email,$client);
$ppic['pic']=$this->Clientmodel->get_pic($email);
$config['upload_path'] = './profile/';
$config['allowed_types'] = 'jpg|jif|png|jpeg';
$this->load->library('upload', $config);
$field = 'pic';
if ($this->upload->do_upload($field)) {
$temp = $this->upload->data();
$pic = $temp['file_name'];
}
$this->load->view('client/pro_header',$ppic);
$this->load->view('client/client_dashboard',$client);
}
This is model file Clientmodel.php
public function add_client_details($email, Array $client)
{
return $this->db->where(['email'=>$email])
->update('clients',$client);
}
public function get_pic($login_email)
{
$q=$this->db->where(['email'=>$login_email])
->get('clients');
return $q->row()->profile_pic;
}
After entering all the data all the fields other than image can be fetched using $this->input->post when i try to fetch 'profile_pic' it returns nothing.And the image file name is also not inserted in database.Field 'profile_pic' is there in table 'clients'
This is the for uploading it's not checking any validation
public function upload_docs () {
if($this->input->post('action') == 'Upload') {
$company_name = $input->post('company_name');
$position = $input->post('position');
$mobile = $input->post('mobile');
$specialist_in = $input->post('specialist_in');
// capture all your variable like this
$file_path = './assets/images/uploads';
if ($_FILES["profile_pic"]["error"] > 0) {
$data['msg'] = 'your message';
} else {
if(!is_dir($file_path)) #mkdir($file_path, 0777, true);
if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], $file_path.'/'.$_FILES['profile_pic']['name'])) {
$upload_data = array('company_name'=> $company_name,'mobile'=> $mobile,'specialist_in'=> $specialist_in,'profile_pic' => $_FILES['profile_pic']['name']);
$insert_id = $this->Your_model->addRecord($upload_data);
if ($insert_id) {
// redirect('admin/index','refresh');
}
}
}
}
$data['title'] = 'upload';
$this->load->view('admin/upload',$data);
}
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()?>