filename return empty codeigniter - php

i have form to upload images in php, when i save the path and name, the name returns empty field in table database here is my code and the value in my database always empty field, please help me
Registration controller
<?php
/**
*
*/
class Registration extends CI_Controller {
function __construct() {
parent::__construct();
//$this->load->library('upload');
$this->load->helper('form');
}
function index() {
$this->load->view('/registration/daftar');
}
function add_user() {
$this->load->model('/daftar/Daftar_Model');
$image_path = APPPATH. 'user_images/';
$config['upload_path'] = $image_path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500';
$config['max_height'] = '450';
$config['max_width'] = '450';
//$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$path = $this->upload->data();
$image_name1 = $path['file_name'];
$image_path1 = $path['file_path'];
//$this->upload->do_upload('foto');
//$photo_data = $this->upload->data();
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'),
'no_telepon' => $this->input->post('no_telepon'),
'alamat' => $this->input->post('alamat'),
'image_path' => $image_path1,
'image_name' => $image_name1
);
$this->db->select('username');
$this->db->where('username', $data['username']);
$result = $this->db->get('user');
if($result->num_rows() > 0) {
echo "Udah ada";
$this->output->set_header('refresh:2; url='.site_url("/registration"));
} else {
if(! $this->upload->do_upload('foto')) {
var_dump($this->upload->display_errors());
//$this->load->view('/registration/daftar', $error);
} else {
//$data1 = array('upload_data' => $this->upload->data());
$this->Daftar_Model->insert($data);
echo "Registrasi Berhasil";
$this->output->set_header('refresh:2; url='.site_url("/login"));
//$this->load->view('/registration/daftar', $data1);
}
}
}
}
this is my form
<html>
<head>
<title>Daftar</title>
<body>
<?php
?>
<h1><center>Daftar</center></h1>
<?php echo form_open_multipart('registration/registration/add_user'); ?>
<center>
Username <br>
<input type="text" name="username"> <br>
Password <br>
<input type="password" name="password"> <br>
Email <br>
<input type="text" name="email"> <br>
No Telepon <br>
<input type="text" name="no_telepon"> <br>
Alamat <br>
<textarea name="alamat" rows="6" cols="23"></textarea> <br>
</form>
Foto
<input type="file" name="foto"><br><br><br>
<input type="submit" name="submit" value="Daftar">
</center>
</form>
</body>
</head>
</html>

Are you check your function add_user()?
I suggested you to check upload status before you can add to database. If your upload code error, they will show you error and then you will know where to fix it. It should be:
if(!$this->upload->do_upload('foto'))
{
// Print the upload error
var_dump($this->upload->display_errors());
}else{
$return = $this->upload->data();
$image_name = $return['file_name'];
// your code add to database
}
Hope this help.

Related

How to send multiple file upload in codeigniter?

I want to insert data with multiple file, but the file is null if i insert to database. this is my code
FROM ACTION CODE
<form action="<?php echo base_url();?>SystemCore/tambahKendaraan" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Foto Foto Kendaraan</label>
<input type="file" class="form-control" multiple="" required="" name="addKendaraanDinasFoto[]">
<small>*Dapat Mencantumkan Foto Lebih Dari 1</small>
</div>
<button type="submit" class="btn btn-success">Simpan</button>
</form>
This i my Controller to upload data
public function tambahKendaraan()
{
$simpanData = array(
"id_jenis" => $this->input->post("addKendaraanDinasJenis"),
"plat_kendaraan" => $this->input->post("addKendaraanDinasPlat"),
"dinas_pengelola" => $this->input->post("addKendaraanDinasPengelola"),
"pemegang_kendaraan" => $this->input->post("addKendaraanDinasPemegang"),
"no_stnk" => $this->input->post("addKendaraanDinasSTNK"),
"no_rangka" => $this->input->post("addKendaraanDinasRangka"),
"masa_pajak" => $this->input->post("addKendaraanDinasPajak"),
"merk_kendaraan" => $this->input->post("addKendaraanDinasMerk"),
"warna_kendaraan" => $this->input->post("addKendaraanDinasWarna"),
"status_kendaraan" => $this->input->post("addKendaraanDinasStatus"),
);
if ($this->db->insert("tbl_mobil", $simpanData)) {
$insert_id = $this->db->insert_id();
date_default_timezone_get("Asia/Jakarta");
$this->load->library('upload');
$dataInfo = array();
$files = $_FILES;
$cpt = count($_FILES['addKendaraanDinasFoto']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['addKendaraanDinasFoto']['name']= $files['addKendaraanDinasFoto']['name'][$i];
$_FILES['addKendaraanDinasFoto']['type']= $files['addKendaraanDinasFoto']['type'][$i];
$_FILES['addKendaraanDinasFoto']['tmp_name']= $files['addKendaraanDinasFoto']['tmp_name'][$i];
$_FILES['addKendaraanDinasFoto']['error']= $files['addKendaraanDinasFoto']['error'][$i];
$_FILES['addKendaraanDinasFoto']['size']= $files['addKendaraanDinasFoto']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$dataInfo[] = $this->upload->data();
$this->db->insert("tbl_fotomobil", $data);
}
foreach ($dataInfo as $infos) {
$data = array(
'id_mobil' => $insert_id,
'tgl_foto' => date('Y-m-d H:i:s'),
'foto_mobil' => $infos['file_name'],
);
}
$this->session->set_flashdata('notif', '<script>swal ( "Success" , "Data Kendaraan Berhasil Ditambahkan !" , "success" );</script>');
}else{
$this->session->set_flashdata('notif', '<script>swal ( "Error" , "Data Error !" , "error" );</script>');
}
redirect('kendaraan');
}
private function set_upload_options()
{
$config = array();
$config['upload_path'] = './upload/kendaraan/';
$config['allowed_types'] = 'jpg|png|jpeg|svg';
$config['max_size'] = 10097152;
$config['overwrite'] = FALSE;
return $config;
}
Result:
array(3) {
["id_mobil"]=>
int(0)
["tgl_foto"]=>
string(19) "2019-07-09 09:55:58"
["foto_mobil"]=>
string(0) ""
}
array(3) {
["id_mobil"]=>
int(0)
["tgl_foto"]=>
string(19) "2019-07-09 09:55:58"
["foto_mobil"]=>
string(0) ""
}
Controller :::
public function addmember()
{
if (empty($_FILES['user_image']['name']))
{
$this->form_validation->set_rules('user_image', 'User Image', 'required');
}
if (empty($_FILES['user_gallery']['name']))
{
$this->form_validation->set_rules('user_gallery[]', 'User Gallery', 'required');
}
if($this->form_validation->run() == FALSE)
{
$this->load->view('common_page/header');
$this->load->view('common_page/sidebar');
$this->load->view('form');
$this->load->view('common_page/footer');
}
else
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if($this->upload->do_upload('user_image') && !empty($_FILES['user_gallery']['name']))
{
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
$dataInfo = [];
$files = $_FILES;
$cpt = count($_FILES['user_gallery']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['user_gallery']['name'] = $files['user_gallery']['name'][$i];
$_FILES['user_gallery']['type'] = $files['user_gallery']['type'][$i];
$_FILES['user_gallery']['tmp_name'] = $files['user_gallery']['tmp_name'][$i];
$_FILES['user_gallery']['error'] = $files['user_gallery']['error'][$i];
$_FILES['user_gallery']['size'] = $files['user_gallery']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('user_gallery');
$dataInfo[] = $this->upload->data();
}
$all_imgs = '';
if ( count($dataInfo) > 0) {
foreach ($dataInfo as $info) {
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
$data = [
'user_image' => $uploadedFile,
'user_gallery' => $all_imgs
];
$this->Admin_model->insertData($data,'member');
$this->session->set_flashdata('success', 'Member Register Successfully !!!');
redirect('all/form');
}
else
{
}
}
}
VIEW :::
<form role="form" id="member_form" action="<?php echo
base_url('all/addmember');?>" method="post" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">User Image</label>
<input type="file" id="file" name="user_image">
<?php echo form_error('user_image', '<div class="error">', '</div>'); ?>
</div>
<div class="form-group">
<label for="exampleInputFile">User Gallery Image</label>
<input type="file" id="gallery" name="user_gallery[]" multiple="">
<?php echo form_error('user_gallery', '<div class="error">', '</div>'); ?>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>

Ifile not getting uploaded in the database

i'm trying to upload a file in databse using codeigniter, the image is getting stored in the folder but i'm having issue in storing the data in databse, i don know where
im going wrong. please can any one guide me what im doing wrong ? im new to codeigniter concept.
upload.php(controller)
<?php
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index() {
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('filename')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else {
$data = array('upload_data' => $this->upload->data('filename'),$this->input->post());
$this->Upload_model->saverecords($data);
//$this->load->view('upload_success', $data);
}
}
}
?>
Upload_model.php(model)
<?php
class Upload_model extends CI_Model
{
//Insert
function saverecords($data)
{
//saving records
$this->db->insert('latest_news', $data);
}
}
?>
Upload_form.php(view)
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<form action = "" method = "POST">
<input type = "file" name = "filename" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
</form>
</body>
</html>
You declare <form> twice! Remove <form action = "" method = "POST"> completely and just use the above form_open_multipart:
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="filename" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
Also there is no need for spaces like type = "submit"
Then in your code:
if ( ! $this->upload->do_upload('filename')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else {
//$data = array('upload_data' => $this->upload->data('filename'),$this->input->post());
$data['upload_data'] = $this->upload->data('file_name');
$this->load->model('upload_model');
$this->upload_model->saverecords($data);
//$this->load->view('upload_success', $data);
}
For future:
Do not just do $this->input->post() to assign the key value pairs to those in db. It is not very controlled and can lead to issues. Instead just define it. So if you add other data it would look something like:
$data = array(
'example1_fieldname' => $this->input->post('example1_fieldname');
'upload_data' => $this->upload->data('file_name');
);

Image update in codeigniter

I have an issue updating images for my posts in CodeIgniter.
I have no probleme creating posts with images, but when I try to update a post, post changed info are updated bu not the image.
I have tried several posibilities from different tutorials without success
Thanks in advance
Here is my code:
controller
public function create(){
if(!$this->session->userdata('logged_in'))
{
redirect('users/login');
}
$data['title'] = 'Create Post';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
if($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
}
else
{
$slug = url_title($this->input->post('title'));
$post_image = $this->upload_image();
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'body' => $this->input->post('body'),
'post_image' => $post_image
);
//$this->post_model->create_post($post_image);
$this->post_model->create_post($data);
// Set message
$this->session->set_flashdata('post_created', 'Your post has been created successfully!');
redirect('posts');
}
}
public function edit($slug)
{
$data['post'] = $this->post_model->get_posts($slug);
// Check if logged user has created this post
if($this->session->userdata('user_id') != $this->post_model->get_posts($slug)['user_id'])
{
redirect('posts');
}
$data['categories'] = $this->category_model->get_categories();
if(empty($data['post']))
{
show_404();
}
$data['title'] = 'Edit Post';
$this->load->view('templates/header');
$this->load->view('posts/edit', $data);
$this->load->view('templates/footer');
}
public function update()
{
// Check login
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$id=$this->input->post("id");
$slug = url_title($this->input->post('title'));
if( $_FILES['userfile']['name']!="" )
{
$post_image = $this->upload_image();
}
else
{
$post_image=$this->input->post('old');
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'body' => $this->input->post('body'),
'post_image' => $post_image
);
//$this->post_model->update_post($post_image);
$this->post_model->update_post($data,$id);
// Set message
$this->session->set_flashdata('post_updated', 'Your post has been updated successfully!');
redirect('posts');
}
public function upload_image()
{
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $config);
if(!$this->upload->do_upload())
{
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
}
else
{
$upload_data=$this->upload->data();
$post_image=$upload_data['file_name'];
}
return $post_image;
}
model:
public function create_post($data)
{
return $this->db->insert('posts', $data);
}
public function update_post($data, $id)
{
$this->db->where('id', $id);
return $this->db->update('posts', $data);
}
view (edit view):
<?php echo form_open('posts/update'); ?>
<input type="hidden" name="id" value="<?php echo $post['id']; ?>">
<input type="hidden" id="old" name="old" value="<?php echo $post['post_image'] ?>">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title" placeholder="Add Title" value="<?php echo $post['title']; ?>">
</div>
<div class="form-group">
<label>Body</label>
<textarea id="editor1" class="form-control" name="body" placeholder="Add Body"><?php echo $post['body']; ?></textarea>
</div>
<div class="form-group">
<label>Change Image</label>
<input class="form-control" type="file" name="userfile" size="20">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I'm not sure how anything is uploading as do_upload() doesn't declare the the name of the file field. In this case I suppose it is userfile e.g. do_upload('userfile').
Consider doing something with you file uploads error variable as this should have uncovered your error rather quickly.
EDIT:
My bad, apparently do_upload() default file name parameter for upload is userfile. My guess now as to why it isn't working is that your "update" form, doesn't use form_open_multipart!
Please note: you can also move your redirect function back to login to the controllers constructor. This will eliminate some lines of duplicate code.
Also if you are looking for an easy way to get the errors of the upload function you can do the following:
private function upload_image()
{
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $config);
if(!$this->upload->do_upload())
{
throw new Exception($this->upload->display_errors());
//$errors = array('error' => $this->upload->display_errors());
//$post_image = 'noimage.jpg';
}
else
{
$upload_data=$this->upload->data();
$post_image=$upload_data['file_name'];
}
return $post_image;
}
Usage:
try {
$this->upload_image();
} catch (Exception $e) {
show_error($e->getMessage());
}

Codeigniter: trying to update profile with codeigniter

I'm new to codeigniter, and I'm trying to make a form that updates a profile. It has worked before but now it doesn't anymore.
I changed something in the view and it stopped working. I changed it back to where it was but it doesn't work anymore. I spend half a day trying to make it work again but I failed.
Maybe I don't see what you guys can see. At least I hope so.
this is my view:
<?php echo form_open_multipart('Gids/do_upload');?>
<img width="200px" src="<?php echo base_url()."uploads/".$profile[0]['image']; ?>" alt=""/>
<label for="">Uploade new picture:</label><input type="file" name="userfile" size="20" value="128.jpg" >
<input style="display: none" id="image" name="image" type="text" value="<?php echo "profile_picture".$_SESSION['id'].".jpg"; ?>"/>
<label for="naam">Naam:</label><input id="naam" name="naam" type="text" value="<?php echo $profile[0]['naam']; ?>"/>
<label for="voornaam">Voornaam:</label><input id="voornaam" name="voornaam" type="text" value="<?php echo $profile[0]['voornaam']; ?>"/>
<label for="email">Gebruikersnaam:</label><input id="gebruikersnaam" name="gebruikersnaam" type="text" value="<?php echo $profile[0]['gebruikersnaam']; ?>"/>
<label for="email">Email:</label><input id="email" name="email" type="text" value="<?php echo $profile[0]['email']; ?>"/>
<label for="opleiding">Opleiding:</label><input id="opleiding" name="opleiding" type="text" value="<?php echo $profile[0]['opleiding']; ?>"/>
<label for="school">School:</label><input id="school" name="school" type="text" value="<?php echo $profile[0]['school']; ?>"/>
<label for="wachtwoord">Wachtwoord:</label><input id="wachtwoord" name="wachtwoord" type="text" />
<label for="typeAgain">Type Opnieuw:</label><input id="typeAgain" type="text" />
<label for="over">Over mezelf:</label><textarea name="over" id="over" cols="30" rows="10"><?php echo $profile[0]['over']?></textarea>
<input type='text' style="display: none" name='student_id' value="<?php echo $profile[0]['student_id']?>"/>
<button class="btn btn-default" id="changeprofile" type="submit">Wijzigingen opslaan</button>
</form>
As you can see there is also a image upload
this is my controller:
function do_upload()
{
$this->load->model("Gids_model",'',true);
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['file_name'] = 'profile_picture'.$_SESSION['id'].'.jpg';
$config['overwrite'] = 'TRUE';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error_upload = array('error' => $this->upload->display_errors());
redirect('Gids/datum', $error_upload);
}
else
{
$this->Gids_model->update_profile($this->input->post('student_id'), $this->input->post('voornaam'), $this->input->post('naam'), $this->input->post('email'), $this->input->post('wachtwoord'), $this->input->post('opleiding'), $this->input->post('school'), $this->input->post('over'), $this->input->post('image'), $this->input->post('gebruikersnaam'));
//$e = $this->input->post('student_id');
$data_upload = array('upload_data' => $this->upload->data());
redirect('Gids/datum', $data_upload);
}
}
And this is my model:
public function update_profile($id, $voornaam, $naam, $email, $wachtwoord, $opleiding, $school, $over, $image, $gebruikersnaam){
$data = array(
'student_id' => $id,
'voornaam' => $voornaam,
'naam' => $naam,
'email' => $email,
'wachtwoord' => $wachtwoord,
'opleiding' => $opleiding,
'school' => $school,
'over' => $over,
'image' => $image,
'gebruikersnaam' => $gebruikersnaam
);
$this->db->where('student_id', $id);
$this->db->update('tbl_student', $data);
}
Could you please help me out.
Also I don't know what the form_open_multipart('Gids/do_upload') is for, I got it from a tutorial to upload images with codeigniter.
Here is what i tried
public function do_upload() {
$this->load->model("Gids_model",'',true);
// load library or you can do it with autoloading
// feature of CI
$this->load->library('upload');
// make sure that the folder uploads is created
// at the root directory of the project
$config = array(
'upload_path' => './uploads',
'allowed_types' => 'jpg|jpeg|JPG|JPEG|png',
'max_size' => '1000',
'file_name' => 'profile_picture.jpg',
'overwrite' => true
);
// use initialize instead
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error_upload = array('error' => $this->upload->display_errors());
// you can check the errors here by using var_dump();
// just uncomment the the line below
// var_dump($this->upload->display_errors());die();
redirect('Gids/datum', $error_upload);
}
else
{
$this->Gids_model->update_profile($this->input->post('student_id'), $this->input->post('voornaam'), $this->input->post('naam'), $this->input->post('email'), $this->input->post('wachtwoord'), $this->input->post('opleiding'), $this->input->post('school'), $this->input->post('over'), $this->input->post('image'), $this->input->post('gebruikersnaam'));
//$e = $this->input->post('student_id');
$data_upload = array('upload_data' => $this->upload->data());
redirect('Gids/datum', $data_upload);
}
}
I tried this and hope it helps:
Controller :
public function upload_profile() {
$input = $this->input->post();
$config['upload_path'] = './uploads/profile_pics/'; //path were I save the uploaded profile pics
$config['allowed_types'] = 'gif|jpg|png'; // allowed types that is mention
//size of the picture by default
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = true;
$this->load->library('upload', $config);
// display error if the picture is not on the config (sample bmp)
if ( ! $this->upload->do_upload())
{
$error = $this->upload->display_errors(); // display the errors
$data['upload_error'] = $error;
if($this->session->userdata('account_id') != null) { // if there is an account
$this->load->model('profile'); //model
$this->load->model('account'); //model
$data['user'] = $this->profile->get_profile($this->session->userdata('account_id')); //get_profile is a function in model
$data['account'] = $this->account->get_account($this->session->userdata('account_id')); //get_account is a function in model
$data['view'] = 'users/settings';
$data['title'] = "User's Settings";
$data['error'] = $error;
$this->load->view('masterpage', $data);
} else {
redirect(base_url('index.php/qablog/login'));
}
}
else
{
//if no error
$data = $this->upload->data();
$updateProfile = array(
'profile_pic' => $data['file_name']
);
$this->load->model('profile');
$this->profile->update_profile($this->session->userdata('account_id'), $updateProfile); // update the profile of the user
redirect(base_url('index.php/users/profile'));
}
}
Model get_profile():
public function get_profile($profile_id)
{
$this->db->select()->from('profile_tbl')->where('profile_id', $profile_id);
$query = $this->db->get();
return $query->first_row('array');
}
Model update_profile():
public function update_profile($profile_id, $data)
{
$this->db->where('profile_id', $profile_id);
$this->db->update('profile_tbl', $data);
return $this->db->affected_rows();
}
Model get_account():
public function get_account($account_id)
{
$this->db->select()->from('account_tbl');
$this->db->where('account_id', $account_id);
$query = $this->db->get();
return $query->result_array();
}
View :
//if there is an error
<?php
if ($error == 3) {?>
<div class="alert alert-success">
×
<strong>Success!</strong> Account or Profile Changed Successfully.
</div>
<?php } else if ($error == 1) { ?>
<div class="alert alert-warning">
×
<strong>Warning!</strong>Password Entered is Incorrect!.
</div>
<?php }else if ($error == 2) { ?>
<div class="alert alert-warning">
×
<strong>Warning!</strong>New Password and Confirm Password!.
</div>
<?php }?>
// default.png if haven't uploaded profile picture
<?php $profilePic = "default.png"; ?>
// if already uploaded profile picture it will display
<?php if($user['profile_pic'] != null) { ?>
<?php $profilePic = $user['profile_pic']; ?>
<?php } ?>
// if there is an error in uploading
<?php if(isset($upload_error)) { ?>
<div class="col-lg-12">
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Uploading profile image could not be completed. <?php print_r($upload_error); ?>
</div>
</div>
<?php } ?>
<div class="col-lg-12">
//display the profile picture
<img src="<?php echo base_url('uploads/profile_pics/'.$profilePic); ?>" width="100" />
// call the controller upload_profile
<?php echo form_open_multipart(base_url('index.php/users/upload_profile'));?>
<input type="file" name="userfile" id="userfile" size="20" style="display:none;" />
<label for="userfile" class="btn btn-info btn-sm">Choose Image</label>
<input type="submit" class="btn btn-xs" value="edit profile" />
</form>
<h3 class="text-info"><?php echo $user['fname'].' '.$user['lname']; ?></h3>
</div>
Just follow this, and if you have problem just tell me. :)

how to Upload image in codeigniter, when submitting all the formfields?

I want to know how can I upload an image and save its name in database when using codeigniter,
I am using simple form tag for this, like,
<form action="" name="add" enctype="multipart/form-data" method="post">
<label for="img">Image: </label> <input type="file" name="image" />
<label for="title">Title: </label> <input type="text" name="photo_title" value="" />
<label for="description">Description: </label>
<textarea name="photo_description"> </textarea>
<label for="photo_category">Category </label>
<select name="photo_category">
<option value="select_one">Please Select..</option>
<option value="fun">Fun</option>
</select>
<input type="submit" value="Add" />
</form>
I check the manual but can't get the point what they are doing , anybody please help me to make a controler function for this that will insert all the values in database and also upload the image file.
Thanks,
Shah Rukh
public function upload() {
$this->load->library('form_validation');
$this->form_validation->set_rules('photo_title', 'Photo Title', 'required');
$this->form_validation->set_rules('photo_description', 'Photo Description', 'required');
$this->form_validation->set_rules('photo_category', 'Photo Category', 'required');
if ($this->form_validation->run() == TRUE) {
$data = array(
'photo_title' => $this->form_validation->set_value('photo_title'),
'photo_description' => $this->form_validation->set_value('photo_description'),
'photo_category' => $this->form_validation->set_value('photo_category'),,
);
$this->db->insert('table_name', $data);
// Start Upload Picture
if (!empty($_FILES['image']['name'])) {
$config['upload_path'] = ''.$_SERVER['DOCUMENT_ROOT'].'/upload_path/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '5000';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$config['encrypt_name'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
$data = array('upload_data' => $this->upload->data());
$data = $this->upload->data();
$this->db->select('id');
$this->db->from('table_name');
$this->db->order_by('id', 'DESC');
$this->db->limit(1);
$query = $this->db->get();
$row = $query->row();
$data1 = array(
'shirt' => $data['file_name'],
);
$this->db->where('id', $row->id);
$this->db->update('table_name', $data1);
}
}
};
}
by using
$this->upload->initialize($config);
instead of
$this->load->library('upload', $config);
Thanks,
Shah Rukh

Categories