Image uploading using codeigniter file uploading class - image

This is not a how to upload image question . I have almost successfully managed to add a image upload function into my add client function . It works well when i try to upload a valid file .. but when i select a invalid file or larger file then it shows undefined variable upload_data and codeigniter database error where img_path is NULL it says Column 'img_path' cannot be null. why this function isn't working $this->upload->display_errors(); . The validation errors are showing nicely but no file validation error showing up.
I am using Codeigniter and hmvc
here is my controller
<?php
class Clients extends MX_Controller{
function __construct(){
parent::__construct();
$this->load->model('mdl_clients');
}
function add(){
$data['success'] = null;
$data['errors']= null;
if($_POST){
$config_arr = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '2048',
'max_width' => '1024',
'max_height' => '768',
'encrypt_name' => true,
);
$this->load->library('upload', $config_arr);
if (!$this->upload->do_upload()) {
$data['errors'] = $this->upload->display_errors(); // this isn't working
} else {
$upload_data = $this->upload->data();
}
$config=array(
array(
'field'=>'firstName',
'label'=>'First Name',
'rules'=>'required|max_length[15]|min_length[3]'
),
array(
'field'=>'city',
'label'=>'City',
'rules'=>'required'
),
array(
'field'=>'mobile_phone',
'label'=>'Mobile Number',
'rules'=>'required'
),
array(
'field'=>'email',
'label'=>'Email',
'rules'=>'required|is_unique[clients.email]|valid_email'
),
);
$this->load->library('form_validation');
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$data=array(
'img_path'=>$upload_data['file_name'],
'firstName'=>$_POST['firstName'],
'email'=>$_POST['email'],
'city'=>$_POST['city'],
'mobile_phone'=>$_POST['mobile_phone'],
);
$this->mdl_clients->add($data);
$data['success'] = 1;
$data['errors']= 0;
}
}
$data['title'] = 'Add Client Database';
$data['main_content'] = 'clients/add';
echo Modules::run('templates/admin', $data);
}
and my view file .. add.php
<? if($success==1) {?>
<div class="alert alert-success">
<a class="close" data-dismiss="alert" href="#">×</a>
Data Has been Updated !
</div>
<? } ?>
<?php if($errors) { ?>
<div class="alert alert-error" >
<a class="close" data-dismiss="alert" href="#">×</a>
<?=$errors?>
</div>
<? } ?>
<?php $attributes = array('class' => 'form-horizontal');
echo form_open_multipart('clients/add', $attributes); ?>
<fieldset>
<!-- Address form -->
<h2>Client Information</h2>
<hr />
All Fields Marked with <span style="color: red;">*</span> is necessary .
<hr />
<!-- Upload input-->
<div class="control-group">
<label class="control-label">Upload<span style="color: red;">*</span></label>
<div class="controls">
<input name="userfile" name="userfile" type="file"
class="input-xlarge">
<p class="help-block"></p>
</div>
</div>
<!-- firstName input-->
<div class="control-group">
<label class="control-label">First Name<span style="color: red;">*</span></label>
<div class="controls">
<input id="firstName" name="firstName" type="text" placeholder="First Name"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- Email input-->
<div class="control-group">
<label class="control-label">E-Mail<span style="color: red;">*</span></label>
<div class="controls">
<input id="email" name="email" type="text" placeholder="A Valid Email Address"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- City input-->
<div class="control-group">
<label class="control-label">City<span style="color: red;">*</span></label>
<div class="controls">
<input id="city" name="city" type="text" placeholder="City Name"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
<!-- Mobile input-->
<div class="control-group">
<label class="control-label">Mobile Number<span style="color: red;">*</span></label>
<div class="controls">
<input id="mobile_phone" name="mobile_phone" type="text" placeholder="Current Mobile Phone Number"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- Button -->
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Add to Database</button>
</div>
</div>
</fieldset>
</form>

Assuming an input element of:
<input type="file" name="image" id="image">
Change the following line:
!$this->upload->do_upload()
to:
!$this->upload->do_upload('image')
Please let me know if you face any problem.
UPDATE
If you want to send it to the template then do something like this:
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg',$error['error']);
redirect('controller_name/function_name','refresh');
}
Let me know if this works for you.

While doing the form validation you are not taking into consideration if there were upload errors or not. You should check if there were upload errors or not than proceed with the form validation
if($data['errors'] != '')
{
//do something, probably redirect back to the view and show the errors
}
else
{
if($this->form_validation->run() == FALSE)
{
$data['errors'] = validation_errors();
}
else
{
$data=array(
'img_path'=>$upload_data['file_name'],
'firstName'=>$_POST['firstName'],
'email'=>$_POST['email'],
'city'=>$_POST['city'],
'mobile_phone'=>$_POST['mobile_phone'],
);
$this->mdl_clients->add($data);
$data['success'] = 1;
$data['errors']= 0;
}
}

Related

Data retrieval in CodeIgniter Form

I have successfully created a registration and login system in Code Igniter.
After registration all the user data is saved in database.
I have used email and password in the login form and I want to display all the details related to that logged user.
I have tried a few things but not getting the exact one. How should I proceed?
//Controller file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller{
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('session', 'form_validation', 'email', 'upload'));
$this->load->database();
$this->load->model('user_model');
}
public function index()
{
$this->load->view('registration');
}
public function registration()
{
//validate input value with form validation class of codeigniter
$this->form_validation->set_rules('fname', 'First Name', 'required|regex_match[/^[A-Za-z]{2,15}+$/]');
$this->form_validation->set_rules('lname', 'Last Name', 'required|regex_match[/^[A-Za-z]{2,15}+$/]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[user.email]');
$this->form_validation->set_rules('phone', 'Phone Number', 'required|regex_match[/^[789]\d{9}$/]');
$this->form_validation->set_rules('city', 'City', 'required|regex_match[/^[A-Za-z]{3,15}+$/]');
$this->form_validation->set_rules('zip', 'Zip Code', 'required|regex_match[/^\d{6}$/]');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[15]');
$this->form_validation->set_rules('confirmpswd', 'Password Confirmation', 'required|matches[password]');
$this->form_validation->set_rules('image', 'Image', 'callback_do_upload','required');
//$this->form_validation->set_message('is_unique', 'This %s is already exits');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('registration', array('error' => ' ' ));
}
else
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$gender = $_POST['gender'];
$password = $_POST['password'];
$passhash = hash('md5', $password);
$image = $_FILES['image']['name'];
//call method for uploading image
$upload = $this->do_upload('image');
//md5 hashing algorithm to decode and encode input password
//$salt = uniqid(rand(10,10000000),true);
$saltid = md5($email);
$data = array('fname' => $fname,
'lname' => $lname,
'email' => $email,
'phone' => $phone,
'city' => $city,
'zip' => $zip,
'gender' => $gender,
'password' => $passhash,
'image' => $image);
if($this->user_model->insertuser($data))
{
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center"> Registration Successful</div>');
redirect(base_url().'user/login');
}
else
{
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">
Something Wrong. Please try again ...</div>');
redirect(base_url());
}
}
}
public function do_upload($data)
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
/*$config['max_size'] = 1000000;
$config['max_width'] = 1024;
$config['max_height'] = 768;*/
//base_url('uploads/')
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
}
return $data;
}
public function login()
{
$this->load->view('login');
}
public function check_login()
{
$email = $_POST['email'];
$pass = hash('md5', $_POST['password']);
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[15]');
if($this->form_validation->run() == FALSE)
{
$this->load->view('login');
}
else
{
$res = $this->user_model->check_user($email , $pass);
if(!empty($res))
{
echo "you are registered";
echo "<br>";
echo "<br>";
echo "your details are as follows: ";
echo "<br>";
echo "<br>";
echo "email:".$email;
echo "<br>";
}
else
{
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">email/password not found</div>');
redirect(base_url().'user/login');
}
}
}
function setSession($userId,$userName) {
$userSession = array('userId'=>$userId,
'userName'=>$userName,
'loggedIn'=>TRUE );
$this->session->set_userdata($userSession);
}
public function logout()
{
$this->session->sess_destroy();
redirect(base_url().'user/login', 'refresh');
}
}
//View File
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registration</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">
.form-box {
max-width: 500px;
position: relative;
margin: 5% auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row">
<div class="form-box">
<div class="panel panel-primary">
<div class="panel-heading text-center">
<h3>Register</h3>
</div>
<?php
echo $this->session->flashdata('msg');
?>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
</div>
</div>
<form action="<?php echo base_url('user/registration');?>" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="fname">First Name</label>
<div>
<input type="text" class="form-control" id="fname" name="fname" placeholder="First Name" required="">
<span class="text-danger"><?php echo form_error('fname'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="fname">Last Name</label>
<div>
<input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" required="">
<span class="text-danger"><?php echo form_error('lname'); ?></span>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="control-label" for="email"> Email</label>
<div>
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required="">
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="phone">Phone Number</label>
<div>
<input type="text" class="form-control" id="phone" name="phone" maxlength="10" placeholder="Phone Number" required="">
<span class="text-danger"><?php echo form_error('phone'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="city">City</label>
<div>
<input type="text" class="form-control" id="city" name="city" placeholder="City" required="">
<span class="text-danger"><?php echo form_error('city'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="zip">Zip Code</label>
<div>
<input type="text" class="form-control" id="zip" name="zip" placeholder="Zip Code" required="">
<span class="text-danger"><?php echo form_error('zip'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="gender">Gender</label>
<div>
<input type="radio" name="gender" value="male" id="gender" checked="true"> Male
<input type="radio" name="gender" value="female" id="gender"> Female
<input type="radio" name="gender" value="transgender" id="gender"> Transgender
<span class="text-danger"><?php echo form_error('gender'); ?></span>
</div>
</div>
</div>
<br>
<div class="col-sm-12">
<div class="form-group">
<label class="control-label" for="pswd">Password</label>
<div>
<input type="password" class="form-control" id="pswd" name="password" placeholder="Password" required="">
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="control-label" for="cn-pswd">Confirm Password</label>
<div>
<input type="password" class="form-control" id="cn-pswd" name="confirmpswd" placeholder="Confirm Password" required="">
<span class="text-danger"><?php echo form_error('confirmpswd'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-offset-5 col-sm-3 btn-submit">
<button type="submit" class="btn btn-success">Register</button>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
Select image to upload:<br>
<input type="file" name="image" id="image">
<br/><br/>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
// Model file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model
{
public function insertuser($data)
{
return $this->db->insert('candidates', $data);
}
public function verifyemail($key)
{
$this->db->where('md5(email)', $key);
return $this->db->update('candidates', $data);
}
public function check_user($email,$pass)
{
$sql = "SELECT id , fname FROM candidates where email = ? and password = ?";
$data = $this->db->query($sql, array($email,$pass));
return ($data->result_array()) ;
}
// Function To Fetch Selected Record
public function show_user_id($data){
$this->db->select('*');
$this->db->from('candidates');
$this->db->where('email', $data);
$q=$this->db->get('candidates');
return $q->row_array();
}
// Update Query For Selected Student
public function update_user_id1($id,$data){
$this->db->where('email', $id);
$this->db->update('candidates', $data);
}
}
?>
// While registering time your are using md5 encryption for password but while
// retrieving time you are passing password without encryption formate
$data = $this->db->query($sql, array($email,$pass));
// Use this in your model
$data = $this->db->query($sql, array($email,hash('md5', $pass)));

How to upload Multiple files with multiple inputs Using CodeIgniter

plaese help me dear,
I have a form where i want to upload files with multiple inputs(employee_name,resume,offer_letter,joining_letter)
using codeigniter.
My form looks like:
<form class="form-horizontal form-bordered" action="<?php echo base_url('save_employee/');?>" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">Employee Image</label>
<input type="file" class="form-control" name="employee_name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Resume/CV</label>
<input type="file" class="form-control" name="resume">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Offer letter</label>
<input type="file" class="form-control" name="offer_letter">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Joining Letter</label>
<input type="file" class="form-control" name="joining_letter">
</div>
</form
Put This In Your Controller Here Taking Four fields To Upload The Files
public function Add() {
$data = array();
$config = array(
'upload_path' => 'upload',
'allowed_types' => 'gif|jpg|png',
'max_size' => 250,
'max_width' => 1920,
'max_heigh' => 1080,
);
$this->load->library('upload', $config);
if($this->input->post('Submit')) {
$file_data = $this->upload->data();
$data['cnic_img'] = $file_data['file_name'];
$file_data = $this->upload->data();
$data['domcie_img'] = $file_data['file_name'];
$file_data = $this->upload->data();
$data['profile_img'] = $file_data['file_name'];
$file_data = $this->upload->data();
$data['report_img'] = $file_data['file_name'];
$lat_id = $this->your_model->save($data);
}
$this->load->View('your_template');
}
Put This In You Model
function save($data){
$this->db->insert('your_table', $data);
return $this->db->insert_id();
}
Here Is Your View
<div class="portlet-body form">
<!-- BEGIN FORM-->
<?php echo $this->upload->display_errors(''); ?>
<form class="form-horizontal" action="" <?php echo form_open_multipart();?>
<div class="form-group">
<label for="CNIC Image" class="col-md-3 control-label">CNIC Image:</label>
<div class="col-md-9">
<input type="file" id="cnic_img" name="cnic_img">
<p class="help-block">
Upload CNIC image Here.
</p>
</div>
</div>
</div>
</div>
<div class="portlet-body form">
<div class="form-body">
<div class="form-group">
<label for="Domicile Image" class="col-md-3 control-label">Domicile Image:</label>
<div class="col-md-9">
<input type="file" id="domcie_img" name="domcie_img">
<p class="help-block">
Upload Domicile Image Here.
</p>
</div>
</div>
</div>
</div>
<div class="portlet-body form">
<div class="form-body">
<div class="form-group">
<label for="Domicile Image" class="col-md-3 control-label">Profile Image:</label>
<div class="col-md-9">
<input type="file" id="profile_img" name="profile_img" >
<p class="help-block">
Upload Profile Image Here.
</p>
</div>
</div>
</div>
</div>
<div class="portlet-body form">
<div class="form-body">
<div class="form-group">
<label for="Domicile Image" class="col-md-3 control-label">Police validation Report:</label>
<div class="col-md-9">
<input type="file" id="report_img" name="report_img">
<p class="help-block">
Upload Police Validation Report Here.
</p>
</div>
</div>
</div>
</div>
This example is helped for some peoples.
$file = $_FILES;
$config['upload_path'] = './images/product/';
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = 2000;
$config['max_width'] = 1500;
$config['max_height'] = 1500;
$config['encrypt_name'] = TRUE;
if (empty($file['product_image']['name'])) {
$this->form_validation->set_rules('product_image', 'Product image', 'required');
} else {
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('product_image')){
$fileData = $this->upload->data();
} else {
$web['error']['product_image'] = $this->upload->display_errors();
$this->load->view('web_template',$web);
}
}
if (empty($file['customer_image']['name'])) {
$this->form_validation->set_rules('customer_image', 'Customer image', 'required');
} else {
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('customer_image')){
$cusfileData = $this->upload->data();
} else {
$web['error']['customer_image'] = $this->upload->display_errors();
$this->load->view('web_template',$web);
}
}
Get the image file name to insert data
$data = array(
'product_image' => $fileData['file_name'],
'customer_image' => $cusfileData['file_name']
);

how to compare current and old password both are same or not before updation in DB using Codeigniter

I used this HTML for developing Form
<form method="post" action="<?php echo site_url('patients/change_patient_password'); ?>/<?php echo $this->session->userdata('patientDiseasesId'); ?>" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Current Password</label>
<div class="col-md-4">
<input type="text" required class="form-control" name="password" placeholder="Current Password">
<?php $pass = form_error('password'); if(isset($pass)): ?><span class="help-block"><?php echo form_error('password'); ?></span><?php endif; ?>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">New Password </label>
<div class="col-md-4">
<input type="text" required class="form-control" name="password_confirm" placeholder="New Password">
<?php $pass_confirm = form_error('password_confirm'); if(isset($pass_confirm)): ?><span class="help-block"><?php echo form_error('password_confirm'); ?></span><?php endif; ?>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">ReType New Password</label>
<div class="col-md-4">
<input type="text" required class="form-control" name="password_confirm2" placeholder="ReType New Password">
<?php $pass_confirm2 = form_error('password_confirm2'); if(isset($pass_confirm2)): ?><span class="help-block"><?php echo form_error('password_confirm2'); ?></span><?php endif; ?>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Update Password</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
also please have a look my code controller.
public function change_patient_password($patientId){
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('password', 'Password', 'required|is_unique[patients.password]');
$this->form_validation->set_rules('password_confirm', 'New Password', 'required|matches[password_confirm2]');
$this->form_validation->set_rules('password_confirm2', 'ReType New Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->change_patient_password_form();
}
else
{
$this->load->model('patients_model');
$data['password_updated'] = $this->patients_model->change_patient_password_model($patientId);
if($data['password_updated']==true){
$data['success']=true;
$data['main_content']= 'change_patient_password_form';
$this->load->view('includes/patient_template',$data);
}else{
$data['error']=true;
$data['main_content']= 'change_patient_password_form';
$this->load->view('includes/patient_template',$data);
}
}
here is the final model code
public function change_patient_password_model($patientId){
$data = array(
'password' => md5($this->input->post('password_confirm'))
);
$this->db->where('patientDiseasesId', $patientId);
return $this->db->update('patients', $data);
}
I see you're using "is_unique" in your form validation. Will each password be unique?
How I would do this, is to query the DB before we update it, and check if the passwords match. Like so.
public function change_patient_password_model($patientId)
{
// Get this users info
$query = $this->db->get_where('patients', array('patientDiseasesId' => $patientId));
if($query->num_rows() > 0)
{
// We have the patient, so check if the passwords match
$current_password = $query->row('password');
$inputted_password = md5($this->input->post('password_confirm'));
if( $current_password != $inputted_password)
{
// They are not the same, so update it...
$data['password'] = $inputted_password;
$this->db->where('patientDiseasesId', $patientId);
return $this->db->update('patients', $data);
}
else
{
// They are the same...
return false;
}
}
else
{
// No patients with this ID
return false;
}
}
I hope this helps.

updating data in codiegniter with out selecting the file field in form

I am updating the data in database where I have images file too .So what i want is to put the condition on the image input field if the user want to update data as well as the image so the image will be updated accordingly and if user don't want to update image the rest of the data will be updated now I am having problem in getting the image input field data in controller. I am unable to get the filename directly in controller please help me out.
Here is the code.
function save_update()
{
$id=$this->input->post('id');
if(!empty($_FILES['userfile']['name']))
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_successful', $error);
}
else
{
$data1 = $this->upload->data();
$filename=$data1['file_name'];
$data=array(
'pname'=>$this->input->post('product_name'),
'pprice'=>$this->input->post('product_price'),
'pquantity'=>$this->input->post('product_quantity'),
'pcategory'=>$this->input->post('category'),
'product_pic'=>$filename
);
$result=$this->cartmodel->update_data($data,$id,'product');
}
}
else
{
$data=array(
'pname'=>$this->input->post('product_name'),
'pprice'=>$this->input->post('product_price'),
'pquantity'=>$this->input->post('product_quantity'),
'pcategory'=>$this->input->post('category'),
'product_pic'=>$this->input->post('oldfile')
);
$result=$this->cartmodel->update_data($data,$id,'product');
if($result==true)
{
redirect('cart/admin');
}
else
{
echo '<script type="text/javascript">alert("sorry Could\'nt delete the file")</script>';
}
}
}
Html is here.
<form class="form-horizontal" method="post" action="<?php echo base_url(); ?>cart/save_update" enctype="multipart/form-data">
<?php
if(isset($specific))
{?>
<fieldset>
<legend>Form Components</legend>
<div class="control-group">
<label class="control-label" for="project_tittle">Product Name</label>
<div class="controls">
<input type="text" class="span6" id="typeahead" name="product_name" value=
"<?=$specific->pname; ?>">
</div>
</div>
<input type="hidden" name="id" value="<?=$specific->pid ?>">
<div class="control-group">
<label class="control-label" for="project_name">Price </label>
<div class="controls">
<input type="text" class="span6" id="typeahead" name="product_price"
value=
"<?=$specific->pprice; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="project_caption">Quantity </label>
<div class="controls">
<input type="number" class="span6" id="typeahead" name="product_quantity"
value=
"<?=$specific->pquantity; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="project_link">Category </label>
<div class="controls">
<select name="category">
<option value=
"<?=$specific->pcategory; ?>"><?=$specific->pcategory; ?></option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="userfile">Product Pic </label>
<div class="controls">
<input type="file" class="span6" id="typeahead" name="userfile" >
</div>
</div>
<input type="hidden" name="oldfile" value="<?=$specific->product_pic; ?>" >
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<button type="reset" class="btn">Cancel</button>
</div>
</fieldset>
<?php
}
?>
</form>
Replace
if(!empty($_FILES['userfile']['name']))
With
if(isset($_FILES['userfile']))
It is best practice to use isset() to see whether the data is being set or not
Replace
if ( ! $this->upload->do_upload())
With
if ( ! $this->upload->do_upload($_FILES['userfile']['name']))

upload image got error in codeigniter

what im trying to do is Im trying to upload an image to database but I dont know what is the reason why I've got an error like
Message: Undefined index: userfile
Message: Undefined variable: images
in my view. as you can see the name of the input file set as an array same as other tutorial
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<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>
<h3 class="modal-title">Person Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input name="firstName" placeholder="First Name" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<input type="file" name="userfile[]" id="file" class="form-control">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select name="gender" class="form-control">
<option value="">--Select Gender--</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<textarea name="address" placeholder="Address" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input name="dob" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal
in my controller.
public function image()
{
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']); //this is line that has an error, the Message: Undefined index: userfile
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
}
$fileName = implode(',',$images); // the line that has an error, Message: Undefined variable: images
return $fileName;
}
public function ajax_add()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
'image' => $this->input->post($this->image()),
);
$insert = $this->person->save($data);
echo json_encode(array("status" => TRUE));
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
public function ajax_update()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
// 'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
);
$this->person->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
I want to insert that image name to my database but that errors block me to do that... need help.
In your Ajax Request Please add
$("#form").submit(function(e){
e.preventDefault();
var fd = new FormData();
$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
data: formData,
So on....
//ajax close
});
And DOnt Forgot to use
enctype="multipart/form-data"
On form tag...And You will be fine
For Undefined variable: images
Please put
$images = array();// just before for loop.
$cpt = count($_FILES['userfile']);

Resources