Trying to fetch image from database in codeigniter - codeigniter

I was uploaded Image in database Successfully. But not succeed to fetch image from database.
i want to fetch the image from database.
here is my code,
controller -> login.php
public function user_update(){
$this->load->model('login_model');
$this->form_validation->set_rules('fname', 'First Name','required');
$this->form_validation->set_rules('lname', 'Last Name','required');
$this->form_validation->set_rules('cnumber', 'Contact Number','required|min_length[10]|max_length[10]|numeric');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'doc|docx|pdf|gif|jpg|png|xlsx';
$config['max_size'] = 10000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if (( ! $this->upload->do_upload('image')) && ($this->form_validation->run() === FALSE ))
{
$this->load->view('student/home');
}
else
{
$data = array('upload_data' => $this->upload->data());
$image_name=($data['upload_data']['file_name']);
$resume=base_url().$image_name;
$udata = array(
'id' => $this->input->post('id'),
'fname' => $this->input->post('fname'),
'mname' => $this->input->post('mname'),
'lname' => $this->input->post('lname'),
'email' => $this->input->post('email'),
'address' => $this->input->post('address'),
'cnumber' => $this->input->post('cnumber'),
'image'=> $resume
);
$this->login_model->Updateuser($udata);
}
}
model file:- login_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class login_model extends CI_Model
{
function Updateuser($param) {
$id = $param['id'];
$usar1 = array(
'Student_Name' => $param['fname'],
'm_name' => $param['mname'],
'l_name' => $param['lname'],
'Student_Email' => $param['email'],
'contact_no' => $param['cnumber'],
'Address' => $param['address'],
'image' => $param['image']
);
$this->db->where('Student_id', $id);
$this->db->update('students', $usar1);
//echo ($this->db->last_query());
//exit();
$sturesult = $this->login_model->get_student_list();
$data['Stulist'] = $sturesult;
$this->load->view('student/default_list',$data);
}
}
view file:- edit_info.php
<div class="container" id='main-layout' style="border-top: 1px solid #D14B54; background: #f5f5f5f5">
<div class="row">
<div class="col-md-8 col-sm-8">
<div class="ajaxResponse"><input type="hidden" name="ajaxResponse"></div>
<div class="row" style="padding: 10px 5px;">
<?php $id = $this->uri->segment(3); if(!empty($id)): ?>
<div class="">
<?php echo validation_errors();
echo $lname;
?>
<div class="thumbnail familycol" style="padding:16px">
<?php echo form_open_multipart('login/user_update'); ?>
<legend>Personal Information</legend>
<div class="row">
<?php //echo form_label('Id :'); ?> <?php echo form_error('id'); ?>
<input type="hidden" name="id" value="<?php echo $row->Student_id; ?>" class="form-control input-sm" placeholder="id"/>
<!-- <label class="required">First name</label>-->
<div class="col-xs-6 col-md-6">
<label for="First Name">First Name:</label>
<input type="input" name="fname" class="form-control" value="<?php echo $row->Student_Name;?>"/><font color="red"><?php echo form_error('fname'); ?></font>
</div>
<div class="col-xs-6 col-md-6">
<!--<label class="required">Middle name</label>-->
<label for="Last Name">Middle Name:</label>
<input type="input" name="mname" class="form-control" value="<?php echo $row->m_name?>"/><font color="red"><?php echo form_error('mname'); ?></font>
</div>
</div>
<div class="row">
<div class="col-xs-6 col-md-6">
<!--<label class="required">Last name</label>-->
<label for="Last Name">Last Name:</label>
<input type="input" name="lname" class="form-control" value="<?php echo $row->l_name ;?>"/><font color="red"><?php echo form_error('lname'); ?></font>
</div>
<div class="col-xs-6 col-md-6">
<?php echo form_label('Email :'); ?> <?php echo form_error('email'); ?>
<input type="text" name="email" value="<?php echo $row->Student_Email; ?>" class="form-control input-sm" placeholder="Email" />
</div>
</div>
<br>
<div class="row">
<div class="col-sm-6">
<!--<label>Address</label>-->
<label for="text">Address</label>
<textarea name="address" class="form-control"><?php echo $row->Address ;?></textarea><font color="red"><?php echo form_error('address'); ?></font>
</div>
<div class="col-sm-6">
<label for="text">Contact Number</label>
<textarea name="cnumber" class="form-control"><?php echo $row->contact_no ;?></textarea><font color="red"><?php echo form_error('cnumber'); ?></font>
</div>
<br/>
</div>
<br/>
<label for='uploaded_file'>Select A File To Upload:</label>
<input type="file" name="image" accept="image/*" value="upload">
<br/>
<button class="btn btn-lg btn-primary btn-block signup-btn" type="submit" style="margin-top: 5px;">
Update my Profile</button>
</div>
</div>
<?php endif;?>
</div>
</div>
</div>
</div>

Ok Lets Put Code in your View file:
<img src="<?php echo base_url('uploads/').$Stulist[$i]->image; ?>"

You have updated the wrong image directory of uploaded images in database.
Simply update the following lines of code
$data = array('upload_data' => $this->upload->data());
$image_name=($data['upload_data']['file_name']);
$resume=base_url().$image_name;
to
$data = array('upload_data' => $this->upload->data());
$image_name=($data['upload_data']['file_name']);
$resume=base_url('uploads').$image_name;
here the base_url points to the uploads directory where you have uploaded your images.

Related

Item value not updating, Codeigniter

I'm new at using codeigniter and I'm trying to update the item value in my database but it's not working. I can't figure out what to do because when I clicked the save button, the page redirects to the /packages(where the list of packages are displayed) but the item isn't updated. Here's my controller
public function update_package($id)
{
$this->form_validation->set_rules('title', 'Package Name', 'required');
$this->form_validation->set_rules('tour_location', 'Inclusions', 'trim');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('cost', 'Price', 'required');
$this->form_validation->set_rules('status', 'Status', 'required');
if ($this->form_validation->run() == true) {
$current_image = $this->input->post('current_image');
$new_image = $_FILES['image']['name'];
if ($new_image == TRUE) {
$update_image = time() . "-" . str_replace(' ', '-', $_FILES['image']['name']);
$config = [
'upload_path' => './images',
'allowed_types' => 'gif|jpg|png',
'file_name' => $update_image,
];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image')) {
if (file_exists('./images' . $current_image)) {
unlink('./images' . $current_image);
}
}
} else {
$update_image = $current_image;
}
$packageData = array(
'title' => $this->input->post('title'),
'tour_location' => $this->input->post(htmlentities('tour_location')),
'description' => $this->input->post(htmlentities('description')),
'cost' => $this->input->post('cost'),
'status' => $this->input->post('status'),
'upload_path' => $update_image
);
$img = new Admin_model;
$img->update($packageData, $id);
$this->session->set_flashdata('status', 'Package InsertedSuccesfully');
redirect(base_url('admin/edit_package/'.$id));
} else {
return $this->edit_package($id);
}
}
My model
public function update($data, $id) {
// Update member data
return $this->db->update("packages", $data ,array('id' => $id));
}
View
<div class="card-body">
<small><?php echo validation_errors(); ?></small>
<form action="<?= base_url('admin/packages') ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name" class="control-label">Package Name</label>
<input type="text" class="form-control mb-3" name="title" placeholder="Enter Package Name" value="<?php echo !empty($packages->title) ? $packages->title : ''; ?>">
</div>
<div class="form-group">
<label for="short_name" class="control-label">Inclusions</label>
<textarea id="compose-textarea" class="form-control" name="tour_location" style="height: 300px;"><?php echo !empty($packages->tour_location) ? $packages->tour_location : ''; ?></textarea>
</div>
<div class="form-group">
<label for="short_name" class="control-label">Description</label>
<textarea id="compose-textarea2" class="form-control" name="description" style="height: 300px;"><?php echo !empty($packages->description) ? $packages->description : ''; ?></textarea>
</div>
<div class="form-group">
<label for="price" class="control-label">Price</label>
<input type="number" step="any" class="form-control form" required name="cost" value="<?php echo !empty($packages->cost) ? $packages->cost : 0; ?>">
</div>
<div class="form-group">
<label for="status" class="control-label">Status</label>
<select name="status" id="status" class="custom-select select">
<option value="1" <?php echo isset($status) && $status == 1 ? 'selected' : '- Select Status -' ?>>Active</option>
<option value="0" <?php echo isset($status) && $status == 0 ? 'selected' : '- Select Status -' ?>>Inactive</option>
</select>
</div>
<div class="form-group">
<label for="short_name" class="control-label">Images</label>
<div class="custom-file">
<label class="btn custom-file-label text-light" for="customFile">Choose file
<input type="hidden" name="current_image" value="<?php echo !empty($packages->upload_path) ? $packages->upload_path : ''; ?>">
<input type="file" class="form-control custom-file-input" id="customFile" name="image" multiple accept="image/*">
<small><?php if (isset($error)) {
echo $error;
} ?></small>
</label>
</div>
</div>
<div class="col-md-4">
<img src="<?php echo base_url('images/'.$packages->upload_path) ?>" alt="Package Image" class="w-100 h-100">
</div>
<div class="card-footer">
<input type="submit" name="packageData" class="btn btn-success " value="Save">
<a class="btn btn-flat btn-default" href="admin/packages">Cancel</a>
</div>
</form>
</div>
<script>
$("#submit").click(function(e) {
e.preventDefault();
$('#packageData').submit();
});
</script>

Changing password of the signed in user in code igniter

I am working on Code Igniter and stuck in a place where I need to change the password of a signed-in user. I need help in picking up the user id of the signed-in user and through it I want to update the password of that user.
The following are the images of controller and models created of the project respectively.
Create html link:
<i class="fa fa-circle-o"></i>Change password
Create user controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
// Load session library
$this->load->library('session');
$this->load->model('Data_model');
}
public function changePassword()
{
$web = array();
$web['title'] = 'Change password';
$web['content'] = 'web/password';
$this->form_validation->set_rules('old_password', 'Old password', 'required|callback_check_password');
$this->form_validation->set_rules('new_password', 'New password', 'required');
$this->form_validation->set_rules('confirm_password', 'Confirm password', 'required|matches[new_password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('web_template',$web);
} else {
$id = $this->user_id;
$data = array(
'user_password' => $this->input->post('new_password'),
);
$this->Common_model->Data_model('user_login', $data, 'id', $id);
$this->session->set_flashdata('msg', 'Password changed Successfully');
redirect('user/changePassword');
}
}
function check_password($password) {
if($this->user_id)
$id = $this->user_id;
else
$id = '';
$result = $this->Data_model->check_user_password($id, $password);
if($result > 0)
$response = true;
else {
$this->form_validation->set_message('check_password', 'Old password is wrong');
$response = false;
}
return $response;
}
}
Change password html page in view:
<section class="content">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title"><?php echo $title; ?></h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fa fa-minus"></i></button>
</div>
</div>
<?php
$attributes = array('class' => 'form-horizontal', 'id' => 'changePassword');
echo form_open('user/changePassword', $attributes);
?>
<div class="box-body">
<?php if (!empty($this->session->flashdata('msg'))) : ?>
<div class="alert alert-success alert-dismissable alertDiv"> <?php echo $this->session->flashdata('msg'); ?> </div>
<?php endif; ?>
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Old password</label>
<div class="col-md-8">
<input type="password" name="old_password" value="<?php echo (isset($form_data) ? $form_data->old_password : set_value('old_password')); ?>" class="form-control" id="old_password" placeholder="Old password">
<?php echo form_error('old_password', '<div class="error">', '</div>'); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">New password</label>
<div class="col-md-8">
<input type="password" name="new_password" value="<?php echo (isset($form_data) ? $form_data->new_password : set_value('new_password')); ?>" class="form-control" id="new_password" placeholder="New password" autocomplete="off">
<?php echo form_error('new_password', '<div class="error">', '</div>'); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-8">
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Confirm Password</label>
<div class="col-md-8">
<input type="password" name="confirm_password" value="<?php echo (isset($form_data) ? $form_data->confirm_password : set_value('confirm_password')); ?>" class="form-control" id="confirm_password" placeholder="Confirm Password" autocomplete="off">
<?php echo form_error('confirm_password', '<div class="error">', '</div>'); ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-5" style="margin-top: 10px;">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
<?php form_close(); ?>
</div>
<!-- /.box -->
</section>
Create Data_model in model add this function:
// Update data to table
public function update($table, $data, $primaryfield, $id)
{
$this->db->where($primaryfield, $id);
$q = $this->db->update($table, $data);
return $q;
}
//Check the old password:
function check_user_password($id = '', $password) {
$this->db->where('user_password', $password);
$this->db->where('id', $id);
return $this->db->get('user_login')->num_rows();
}

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)));

Can't upload images in Codeigniter

I have a problem with upload images in Codeigniter, when I add a new image an error show ( You did not select a file to upload.) I dont know if miss something in my code
this my function controller:
public function upload_img(){
$this->load->model('esthetique_model');
$config['upload_path'] = realpath(APPPATH.'../upload');
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = '204800';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
foreach ($error as $item => $value){
echo'<ol class="alert alert-danger"><li>'.$value.'</ol></li>';
}
exit;
}else{
$upload_data = $this->upload->data();
$path = $upload_data['file_name'];
$this->esthetique_model->photo_insert_mdl($path);
echo'<h4 style="color:green">Image uploaded Succesfully</h4>';
}
}
my view :
<?php echo form_open('esthetique/upload_img'); ?>
<div class="modal-body">
<!-- hidden input montinned with class sr-only -->
<div class="form-group"><label class="sr-only" =""></label>
<input type="text" name="idsc" class="sr-only" id="idsc" ></div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="userfile">Choisissez l'image</label>
<input type="file" name="userfile" id="userfile">
</div>
</div>
<div class="form-group">
<img id="loader" src="<?php echo base_url() ?>asset/images/486.GIF" style="height: 30px;">
</div>
<div class="form-group">
<img id="preview" src="#" style="height: 80px;border: 1px solid #DDC; " />
</div>
</div>
<div class="form-group ">
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar">
</i>
</div>
<input class="form-control" id="date" name="date" placeholder="Date" type="text"/>
</div>
</div>
<div class="form-group">
<textarea class="form-control" row="3" id="note" name="note" placeholder="Note"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
<button type="submit" class="btn btn-primary">Enregistrer</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
thanks for helping
Try the following (specifying the file input name in your controller):
...
if ( ! $this->upload->do_upload('userfile')) {
...
More information that may be useful: http://www.codeigniter.com/user_guide/libraries/file_uploading.html
I have changed in view
<?php echo form_open('esthetique/upload_img'); ?>
by
<?php echo form_open_multipart('esthetique/upload_img'); ?>
its work now

Image uploading using codeigniter file uploading class

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;
}
}

Resources