How to upload image in codeigniter - php

controller:
public function edit($id) {
$this->edit_status_check($id);
$this->form_validation->set_rules('agent_name', 'Agent Name', 'required');
$this->form_validation->set_rules('mobile', 'Mobile No.', 'required');
$this->form_validation->set_rules('agent_vehicle', 'Agent Vehicle', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => validation_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$config['upload_path'] = '../uploads/agent/';
$config['allowed_types'] = 'jpg|jpeg';
$config['encrypt_name'] = TRUE;
$config['max_size'] = 1000; // 1 mb
$this->load->library('upload', $config);
if (!$this->upload->do_upload('agent_image')) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => $this->upload->display_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$_POST['agent_img_url'] = 'uploads/agent/' . $this->upload->data('file_name');
$this->agent_model->update($_POST, $id);
alert('Update', $_POST['agent_name']);
redirect('agent');
}
}
}
Model:
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['img_url'] = $data['agent_img_url'];
}
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}
View:
<?= form_open_multipart('agent/edit/' . $id); ?>
<?php if (!empty($error)): ?>
<div class="alert alert-danger alert-dismissible" role="alert">
<?= $error; ?>
</div>
<?php endif; ?>
<div class="form-group">
<img src="/<?= $result['img_url']; ?>" class="img-responsive" name="old_agent_image" width="133" height="100">
</div>
<div class="form-group">
<label>Agent Image</label>
<input type="file" name="agent_image">
</div>
<button type="submit" class="btn btn-success">Update</button>
<?= form_close(); ?>
Hi I'm developing a image upload module and image path save in database and retrieve.
my Question I want it to edit and update but the my problem is it doesn't delete the old image in folder, but it save and update the new image.

use file helper of codeigniter
$this->load->helper("file");
delete_files($path);
reference link for you is here

Delete using the file name saved in the database, use the PHP unlink(../filename.jpg) and delete from files

Change in Model
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['agent_img_url'] = $data['agent_img_url'];
}
$q = $this->db->where('id',$id)
->get('agent');
$query = $q->row_array();
#unlink("./asset/uploads/".$query['agent_img_url']);
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}

if (!$this->upload->do_upload($name)) {
$data = array('msg' => $this->upload->display_errors());
} else {
$data = array('msg' => "success");
$databasea['upload_data'] = $this->upload->data();
$this->load->library('image_lib');
return $databasea['upload_data']['file_name'];
}
return '';

Related

how to insert the filename in database and file in folder using codeignator?

I am having a problem with inserting file_path to database and file upload in folder using Codeigniter, I have a form field where user can upload any jpg|png|gif file. But how will I get the file_path of that particular file uploaded and insert it into database and file are stored in floder.
my controller code
public function enqry(){
$data = array();
$postData = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10240;
$this->load->library('upload', $config);
//if add request is submitted
if ( ! $this->upload->do_upload('upload')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('imageUploadForm', $error);
}else {
print_r('Image Uploaded Successfully.');
}
if($this->input->post('postSubmit')){
//form field validation rules
$this->form_validation->set_rules('name', 'post name', 'required');
$this->form_validation->set_rules('email', 'post email', 'required');
$this->form_validation->set_rules('mobile', 'post number', 'required');
$this->form_validation->set_rules('nationality', 'post nationality', 'required');
$this->form_validation->set_rules('location','post location','required');
//prepare post data
$postData = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'nationality' => $this->input->post('nationality'),
'location'=>$this->input->post('location'),
'statuse' => '0',
'created_at' => date("Y-m-d H:i:s")
/*'passport_details'=>$this->input->post('passport_details')*/
);
//validate submitted form data
if($this->form_validation->run() == true){
//insert post data
$insert2 = $this->user_mod->insert_enq($postData);
if($insert2){
$this->session->set_userdata('success_msg', 'Post has been added successfully.');
redirect('/User_con/log/');
}else{
$data['error_msg'] = 'Some problems occurred, please try again.';
}
}
}
$data['post'] = $postData;
$data['title'] = 'Create Post';
}
//load the add page view
public function log_enq(){
$this->load->view('templates/header');
$this->load->view('enquiry_reg');
$this->load->view('templates/footer');
}
My view code
<div class="form-group">
<label for="title">File Upload</label>
<input type="file" name="upload" placeholder="upload">
</div>
My model code
public function insert_enq($data = array()) {
$insert2 = $this->db->insert('tbl_enquiry', $data);
if($insert2){
return $this->db->insert_id();
}else{
return false;
}
}
if (!$this->upload->do_upload('upload')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('imageUploadForm', $error);
}
else {
$data = $this->upload->data('file_name');
$image = 'your_path'.$data;
}
and add $image variable to your your query like
$arrayName = array(
'imapge' => $image,
'more_column' => $more_column_values);
public function enqry(){
$data = array();
$postData = array();
$postData['upload_path'] = './uploads/';
$postData['allowed_types'] = 'gif|jpg|png';
$postData['max_size'] = 10240;
$this->load->library('upload', $postData);
if (!$this->upload->do_upload('upload')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('user_con/error', $error);
}
else {
$data = $this->upload->data('file_name');
$image = 'your_path'.$data;
}
if($this->input->post('postSubmit')){
$this->form_validation->set_rules('name', 'post name', 'required');
$this->form_validation->set_rules('email', 'post email', 'required');
$this->form_validation->set_rules('mobile', 'post number', 'required');
$this->form_validation->set_rules('nationality', 'post nationality', 'required');
$this->form_validation->set_rules('location','post location','required');
$postData = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'nationality' => $this->input->post('nationality'),
'location'=>$this->input->post('location'),
'statuse' => '0',
'created_at' => date("Y-m-d H:i:s"),
'upload' => $image
);
if($this->form_validation->run() == true){
$insert2 = $this->user_mod->insert_enq($postData);
if($insert2){
$this->session->set_userdata('success_msg', 'Post has been added successfully.');
redirect('/User_con/log/');
}else{
$data['error_msg'] = 'Some problems occurred, please try again.';
}
}
}
$data['post'] = $postData;
$data['title'] = 'Create Post';
}
$config = array(
'upload_path' =>'./uploads/',
'allowed_types' =>'jpg|jpeg|png|gif',
'max_size' => '5000KB');
$this->load->library('upload',$config);
$this->upload->initialize($config);
Replace this code your code....and cheack......

Upload issue in Codeigniter with image and text/numbers

First of all sorry for the long post with code, but i feel like i need to explain myself straight. The issue is, i'm trying to insert some data into a database and also the file name in the RESTAURANT_IMAGE column. Everything inserts perfectly fine but the image doesn't upload and the file name is not inserted into the database.
EDIT: Edited the callback function to properly return True or False and now i do the insert in the main function if the callback returns true.
Now i am able to upload the image successfully but still dont get the file name and extension to put into my database.
function restaurant_add()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$config = array(
array(
'field' => 'RestaurantName',
'label' => 'Restaurant Name',
'rules' => 'required|callback_restaurant_check'
),
array(
'field' => 'RestaurantAddress',
'label' => 'Address',
'rules' => 'required'
),
array(
'field' => 'RestaurantReservations',
'label' => 'Reservations',
'rules' => 'max_length[1]|integer'
),
array(
'field' => 'RestaurantWifi',
'label' => 'RestaurantWifi',
'rules' => 'max_length[1]|integer'
),
array(
'field' => 'RestaurantDelivery',
'label' => 'Restaurant Delivery',
'rules' => 'max_length[1]|integer'
),
array(
'field' => 'RestaurantMultibanco',
'label' => 'RestaurantMultibanco',
'rules' => 'max_length[1]|integer'
),
array(
'field' => 'RestaurantImage',
'label' => 'RestaurantImage',
'rules' => ''
)
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('sample_navbar_view');
$this->load->view('restaurant_add');
return FALSE;
}
else
{
$file_name = $this->do_upload();
$data = array(
'RESTAURANT_NAME' => $this->input->post('RestaurantName'),
'RESTAURANT_ADDRESS' => $this->input-> post('RestaurantAddress'),
'RESTAURANT_RESERVATIONS'=> $this->input-> post('RestaurantReservations'),
'RESTAURANT_WIFI'=> $this->input-> post('RestaurantWifi'),
'RESTAURANT_DELIVERY'=> $this->input-> post('RestaurantDelivery'),
'RESTAURANT_MULTIBANCO'=> $this->input-> post('RestaurantMultibanco'),
'RESTAURANT_OUTDOOR_SEATING'=> $this->input-> post('RestaurantOutdoorSeating'),
'RESTAURANT_IMAGE'=> $file_name
);
$this->load->model('restaurant_model');
$this->restaurant_model->restaurant_add($data);
return TRUE;
}
}
Callback function to check if the restaurant name exists, if it does, it doesn't register it, if it doesn't sends the data into the model.
function restaurant_check($restaurantname){
$this->load->model('restaurant_model');
$result = $this->restaurant_model->check_restaurant_name($restaurantname);
if($result > 0) {
return FALSE;
}
else {
return TRUE;
}
}
I used the upload file article present in the Codeigniter Documentation.
View Code:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<?php echo form_open_multipart('restaurant/restaurant_add');?>
<form name="restaurant_add" method="post" action="<?php echo site_url().'Restaurant/restaurant_add'; ?>">
<h2>Register your Restaurant</h2>
<input class="form-control" type="text" class="user" name="RestaurantName" placeholder="Restaurant Name">
<input class="form-control"type="text" class="pass" name="RestaurantAddress" placeholder="Restaurant Address">
<input class="form-control"type="number" class="numero" name="RestaurantReservations" placeholder="Restaurant Rerservations">
<input class="form-control"type="number" class="numero" name="RestaurantWifi" placeholder="Wi-Fi">
<input class="form-control"type="number" class="numero" name="RestaurantDelivery" placeholder="Home Deliveries">
<input class="form-control"type="number" class="numero" name="RestaurantMultibanco" placeholder="Have Multibanco?">
<input class="form-control"type="number" class="numero" name="RestaurantOutdoorSeating" placeholder="Esplanada">
<input class="form-control"type="file" class="image" name="RestaurantImage" placeholder="Upload a Picture">
<div class="container">
<?php echo validation_errors(); ?>
</div>
<button class="btn btn-danger"type="submit">Registar</button>
</form>
</div>
</div>
EDIT: Model Code:
function restaurant_add($info)
{
$query =
"INSERT INTO RESTAURANTS
(RESTAURANT_NAME,RESTAURANT_ADDRESS,RESTAURANT_RESERVATIONS,
RESTAURANT_WIFI,RESTAURANT_DELIVERY,RESTAURANT_MULTIBANCO,
RESTAURANT_OUTDOOR_SEATING,RESTAURANT_IMAGE
)
VALUES
(
'".$info['RESTAURANT_NAME']."',
'".$info['RESTAURANT_ADDRESS']."',
'".$info['RESTAURANT_RESERVATIONS']."',
'".$info['RESTAURANT_WIFI']."',
'".$info['RESTAURANT_DELIVERY']."',
'".$info['RESTAURANT_MULTIBANCO']."',
'".$info['RESTAURANT_OUTDOOR_SEATING']."',
'".$info['RESTAURANT_IMAGE']."'
)
";
$result = $this->db->query($query);
return TRUE;
}
function check_restaurant_name($restaurantname) {
$this->db->trans_begin();
$query = "SELECT RESTAURANT_NAME FROM RESTAURANTS WHERE RESTAURANT_NAME = '".$restaurantname."'";
$result = $this->db->query($query);
$rows = $result->num_rows();
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
return $rows;
}
do_upload() function:
public function do_upload()
{
$config['upload_path'] = './assets/images/restaurantes';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('success_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
$upload_data = $this->upload->data();
//Returns array of containing all of the data related to the file you uploaded.
$file_name = $this->upload->file_name;
return $file_name;
}

Connecting Radio Button to Database using CodeIgniter

I got trouble inputing the radio button value to database, when i choose "submit" it won't add into database. This is the form view:
<?php
$form = array(
'no pengujian' => array(
'name' => 'NO_PENGUJIAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('NO_PENGUJIAN', isset($form_value['NO_PENGUJIAN']))),
'id kendaraan' => array(
'name' => 'ID_KENDARAAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('ID_KENDARAAN', isset($form_value['ID_KENDARAAN']))),
'no kendaraan' => array(
'name' => 'NO_KENDARAAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('NO_KENDARAAN', isset($form_value['NO_KENDARAAN']))),
'lampu' => array(
'name' => 'LAMPU',
'size' => '30',
'class' => 'radio',
'value' => set_value('LAMPU', isset($_POST['LAMPU']))),
'submit' => array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Simpan'
)
);
?>
<h2><?php echo $breadcrumb ?></h2>
<!-- pesan start -->
<?php if (! empty($pesan)) : ?>
<div class="pesan">
<?php echo $pesan; ?>
</div>
<?php endif ?>
<!-- pesan end -->
<!-- form start -->
<?php echo form_open($form_action); ?>
<p>
<?php echo form_label('No Pengujian', 'NO_PENGUJIAN'); ?>
<?php echo form_input($form['no pengujian']); ?>
</p>
<?php echo form_error('NO_PENGUJIAN', '<p class = "field_error">', '</p>');?>
<p>
<?php echo form_label('Id Kendaraan', 'ID_KENDARAAN'); ?>
<?php echo form_input($form['id kendaraan']); ?>
</p>
<?php echo form_error('ID_KENDARAAN', '<p class="field_error">', '</p>'); ?>
<p>
<?php echo form_label('No Kendaraan', 'NO_KENDARAAN'); ?>
<?php echo form_input($form['no kendaraan']); ?>
</p>
<?php echo form_error('NO_KENDARAAN', '<p class="field_error">', '</p>'); ?>
<p>
<?php echo form_label('Lampu', 'LAMPU'); ?>
<input type ="radio" name = "lulus" value="Lulus"/> Lulus
<input type ="radio" name = "lulus" value= "Gagal"/> Gagal
</p>
<p>
<?php echo form_submit($form['submit']); ?>
<?php echo anchor('pengujian', 'Batal', array('class' => 'cancel')) ?>
</p>
<?php echo form_close(); ?>
This is the controller (tambah is "insert" function to database)
<?php if (!defined('BASEPATH')) exit ('No direct script access allowed');
class Pengujian extends MY_Controller
{
public $data = array(
'modul' => 'pengujian',
'breadcrumb' => 'Pengujian',
'pesan' => '',
'pagination' => '',
'tabel_data' => '',
'main_view' => 'view_pengujian/pengujian_view',
'form_action' => '',
'form_value' => '',
'option_uji' => '',
);
public function __construct()
{
parent::__construct();
$this->load->model('Pengujian_model', 'pengujian', TRUE);
$this->load->helper('form');
//$this->load->model('Penguji_model', 'penguji', TRUE);
}
public function index($offset = 0)
{
$this->session->unset_userdata('no_pengujian_sekarang', '');
$pengujian = $this->pengujian->cari_semua($offset);
if ($pengujian)
{
$tabel = $this->pengujian->buat_tabel($pengujian);
$this->data['tabel_data'] = $tabel;
$this->data['pagination'] = $this->pengujian->paging(site_url('pengujian/halaman'));
}
else
{
$this->data['pesan'] = 'Tidak ada data pengujian';
}
$this->load->view('template', $this->data);
}
public function tambah()
{
$this->data['breadcrumb'] = 'Pengujian > Tambah';
$this->data['main_view'] = 'view_pengujian/pengujian_form';
$this->data['form_action'] = 'pengujian/tambah';
//$penguji = $this->penguji->cari_semua();
//if($penguji)
//{
// foreach($penguji as $row)
// {
// $this->data['option_pengujian'][$row->id_penguji] = $row->penguji;
//}
//}
//else
//{
$this->data['option_pengujian']['00'] = '-';
// $this->data['pesan'] = 'Data penguji tidak tersedia. Silahkan isi dahulu data penguji.';
// if submit
if($this->input->post('submit'))
{
if($this->pengujian->validasi_tambah())
{
if($this->pengujian->tambah())
{
$this->session->set_flashdata('pesan', ' Proses tambah data berhasil');
redirect('pengujian');
}
else
{
$this->data['pesan'] = 'Proses tambah data gagal';
$this->load->view('template', $this->data);
}
}
else
{
$this->load->view('template', $this->data);
}
}
else
{
$this->load->view('template', $this->data);
}
}
This is the model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Pengujian_model extends CI_Model
{
public $db_tabel ='pengujian';
public $per_halaman = 100;
public $offset = 0;
public function cari_semua($offset = 0)
{
if (is_null($offset) || empty($offset))
{
$this->offset = 0;
}
else
{
$this->offset = ($offset * $this->per_halaman) - $this->per_halaman;
}
return $this->db->select('NO_PENGUJIAN, ID_KENDARAAN, NO_KENDARAAN, LAMPU, EMISI, REM, WAKTU_UJI')
->from($this->db_tabel)
->limit($this->per_halaman, $this->offset)
->order_by('NO_PENGUJIAN', 'ASC')
->get()
->result();
}
public function buat_tabel($data)
{
$this->load->library('table');
$tmpl = array('row_alt_start' => '<tr class="zebra">');
$this->table->set_template($tmpl);
$this->table->set_heading('No', 'No Pengujian', 'Id Kendaraan', 'No Kendaraan', 'Lampu','Emisi','Rem', 'Waktu Uji', 'Aksi');
$no = 0 + $this->offset;
foreach ($data as $row)
{
$this->table->add_row(
++$no,
$row->NO_PENGUJIAN,
$row->ID_KENDARAAN,
$row->NO_KENDARAAN,
$row->LAMPU,
$row->EMISI,
$row->REM,
$row->WAKTU_UJI,
anchor('pengujian/edit/'.$row->NO_PENGUJIAN,'Edit',array('class' => 'edit')).' '.
anchor('pengujian/hapus/'.$row->NO_PENGUJIAN,'Hapus',array('class' => 'delete','onclick'=>"return confirm('Anda yakin menghapus data ini?')")));
}
$tabel = $this->table->generate();
return $tabel;
}
public function paging($base_url)
{
$this->load->library('pagination');
$config = array(
'base_url' => $base_url,
'total_rows' => $this->hitung_semua(),
'per_page' => $this->per_halaman,
'num_links' => 4,
'use_page_number' => TRUE,
'first link' => '|< First',
'last link' => 'Last >|',
'next link' => 'Next >',
'prev_link' => '< Prev',
);
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
public function hitung_semua()
{
return $this->db->count_all($this->db_tabel);
}
private function load_form_rules_tambah()
{
$form = array(
array(
'field' => 'NO_PENGUJIAN',
'label' => 'no pengujian',
'rules' => 'required'
),
array(
'field' => 'ID_KENDARAAN',
'label' => 'id kendaraan',
'rules' => 'required'
),
array(
'field' => 'NO_KENDARAAN',
'label' => 'no kendaraan',
'rules' => 'required'
),
array(
'field' => 'LAMPU',
'label' => 'lampu',
'rules' => 'required'
),
);
return $form;
}
public function validasi_tambah()
{
$form = $this->load_form_rules_tambah();
$this->form_validation->set_rules($form);
if($this->form_validation->run())
{
return TRUE;
}
else
{
return FALSE;
}
}
public function tambah()
{
$pengujian = array(
'NO_PENGUJIAN' => $this->input->post('NO_PENGUJIAN'),
'ID_KENDARAAN' => $this->input->post('ID_KENDARAAN'),
'NO_KENDARAAN' => $this->input->post('NO_KENDARAAN'),
'LAMPU' => $this->input->post('lampu[]'),
//'EMISI' => $this->input->post('EMISI'),
//'REM' => $this->input->post('REM')
);
$lulus = $_POST["lulus"];
//$statement = "INSERT INTO pengujian VALUES($lulus)"
$this->db->insert($this->db_tabel, $pengujian);
if($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
I got no trouble in the formfield. The trouble is the radio button "lampu"
The best thing to do, I think, is to check where it's going wrong. I usually do this, in this case, by checking if the value is being passed back to the controller and model. This way you understand better what's going on inside your code. Do something like this:
In the model:
public function tambah()
{
// Check to see if we get a value. If not, do the same in the controller
var_dump($this->input->post('lampu'));
exit;
$pengujian = array(
'NO_PENGUJIAN' => $this->input->post('NO_PENGUJIAN'),
'ID_KENDARAAN' => $this->input->post('ID_KENDARAAN'),
'NO_KENDARAAN' => $this->input->post('NO_KENDARAAN'),
'LAMPU' => $this->input->post('lampu[]'),
//'EMISI' => $this->input->post('EMISI'),
//'REM' => $this->input->post('REM')
);
$lulus = $_POST["lulus"];
//$statement = "INSERT INTO pengujian VALUES($lulus)"
$this->db->insert($this->db_tabel, $pengujian);
if($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
I hope this helps a bit....

update statement breaking the database

I am trying to figure out what's wrong here, but really not sure. I have a site with users, when a user edits details, it seems to override all other records with those details. This doesn't happen always but sometimes (of course the result is chaos!). Here is the code of update
public function update_edit()
{
/* echo " //// INSIDE UPDATE EDIT "; */
$this->form_validation->set_rules('fullname', 'الاسم الكامل', 'isset|required|min_length[6]|max_length[100]');
//check that there are no form validation errors
if($this->form_validation->run() == FALSE)
{
/* echo " //// INSIDE FORM VALIDATION"; */
if(($this->session->userdata('username')!=""))
{
/* echo " //// INSIDE SESSION VALIDATION"; */
$data = array();
$data = $this->profileModel->load_user_editable_data($this->session->userdata('username'));
$this->load->view('layout/header');
$this->load->view('profile_edit', $data);
$this->load->view('layout/footer');
//$this->load->view('thankyou');
}else{
//$this->load->view('login');
$this->login();
}
}else{
$complete = $this->profileModel->update_profile($this->session->userdata('username'));
if($complete == 1)
{
$this->load->view('layout/header');
$this->load->view('update_complete');
$this->load->view('layout/footer');
}
}
}
This is the model code:
public function update_profile($username)
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$fullImagePath;
if (isset($_FILES['profilepic']) && !empty($_FILES['profilepic']['name']))
{
if ($this->upload->do_upload('profilepic'))
{
$upload_data = $this->upload->data();
$fullImagePath = '/uploads/' . $upload_data['file_name'];
}
}else{
$fullImagePath = $this->session->userdata('profilepic');
}
$data = array(
'fullname' => $this->input->post('fullname'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'telephone' => $this->input->post('telephone'),
'about' => $this->input->post('about'),
'address' => $this->input->post('address'),
'profilepic' => $fullImagePath,
);
$this->db->where('username', $username);
$this->db->update('free_user_members', $data);
return 1;
}
and this is the form:
<div class="content_container">
<div id="rt-main" class="mb8-sa4">
<div class="rt-container">
<div class="rt-grid-12">
<div dir="rtl" class="homecontent">
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('profile/update_edit'); ?>
<? $this->session->set_userdata('profilepic', $profilepic); ?>
<h5>الاسم الكامل</h5>
<? $data = array(
'name' => 'fullname',
'id' => 'round_input',
'value' => $fullname,
);
echo form_input($data); ?>
<h5>الايميل</h5>
<? $data = array(
'name' => 'email',
'id' => 'round_input',
'value' => $email,
'size' => '70'
);
echo form_input($data); ?>
<h5>الجوال</h5>
<? $data = array(
'name' => 'mobile',
'id' => 'round_input',
'value' => $mobile,
);
echo form_input($data); ?>
<h5>هاتف</h5>
<? $data = array(
'name' => 'telephone',
'id' => 'round_input',
'value' => $telephone,
);
echo form_input($data); ?>
<h5>العنوان</h5>
<? $data = array(
'name' => 'address',
'id' => 'round_input',
'value' => $address,
'size' => '70'
);
echo form_input($data); ?>
<h5>نبذة عني</h5>
<? $data = array(
'name' => 'about',
'id' => 'round_input',
'value' => $about,
'rows' => '3',
'cols' => '40',
);
echo form_textarea($data); ?>
<h5>الصورة الشخصية</h5>
<img width="300" height="300" src="<? echo $profilepic; ?>" />
<h5>إختيار صورة جديدة</h5>
<?
$data = array(
'name' => 'profilepic',
'id' => 'profilepic',
);
echo form_upload($data);
?>
<div><input type="submit" value="احفظ التغييرات" /></div>
</form>
</div>
<p> </p>
</div>
</div>
<div class="clear"></div>
</div>
</div>
will really appreciate it if someone tells me what I am doing that could lead to that chaos every now and then.
Regards,
You have to add code to check that username in the session exists.
If the session times out, codeigniter will return FALSE.
Querying MySQL on username = false will return all rows.

Codeigniter- form with optional file uploading field working unexpectedly

I have a form which asks for user's name and description and an optional field of image uploading. When the user uploads the image I want the name of the image to be changed and stored into the database and if no image is uploaded then a default name is stored in the database. It works fine if user uploads an image but if he does not then nothing is being uploaded into the database.
This is the controller function :
function store()
{
$this->load->model('campus_m');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = preg_replace('/[^a-z0-9]+/i','-',iconv('UTF-8','ASCII//TRANSLIT',$this->input->post('name')));
$config['file_name'] = trim($config['file_name'],'-').now().'.jpg';
$this->load->library('upload', $config);
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('goods', 'Goods', 'required');
$this->form_validation->set_rules('name', 'Name', 'required|max_length[12]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('campus_write_v');
}
else
{
print_r($_FILES['userfile']);
if (empty($_FILES['userfile'])) {
if(!$query = $this->campus_m->create_review("Marla-overdoses1360186300.jpg")){
$data['write_campus'] = 'The answer has not been stored.';
$this->load->view('campus_write_v', $data);
}
else {
$data['write_campus'] = 'The answer has been stored. ';
$this->load->view('campus_write_v', $data);
}
}
else
{
if($this->upload->do_upload()){
if(!$query = $this->campus_m->create_review($config['file_name'])){
$data['write_campus'] = 'The answer has not been stored.';
$this->load->view('campus_write_v', $data);
}
else {
$data['write_campus'] = 'The answer has been stored. ';
$this->load->view('campus_write_v', $data);
}
}
else
{
$error = array('error' => $this->upload->display_errors());
foreach ($error as $rows => $r)
{
echo $r ;
}
$this->load->view('campus_write_v');
}
}
}
}
And this is the view :
<?php
$attributes = array('id' => 'contactform');
echo form_open_multipart('campus/store', $attributes);
?>
<div>
<?php
echo form_label('Title of Area');
$data = array(
'name' => 'name',
'id' => 'name',
'placeholder' => 'Location and name of the place',
'required' => 'required',
'value' => set_value("name")
);
echo form_input($data);
?>
</div>
<div>
<?php
$data = array(
'name' => 'goods',
'id' => 'goods',
'placeholder' => 'Tell us about the place',
'required' => 'required',
'value' => set_value("goods"),
'rows' => '20',
'cols' => '50'
);
echo form_textarea($data);
?>
</div>
<div>
<input type="file" id="userfile" name="userfile" size="20" />
</div>
<div>
<?php
$data = array(
'class' => 'button',
'value' => 'Submit',
'id' =>"submit"
);
echo form_submit($data);
?>
</div>
<?php echo form_close();
?>
</div>
I will solve this in this way:
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload');
$this->upload->initialize($config);
if($this->upload->do_upload('userfile')){
$data = $this->upload->data();
$photo['image'] = $data['file_name']; // Name of image
} else {
$photo['image'] = "Name"; // Name that you want
}
This is the short code of uploads controller.

Categories