I have an updateform with an file input for adding a picture. What i'm trying to achieve is when I leave that field empty, the file will not be changed. So the photo I've uploaded earlier will stay in there.
My forminput is called: <td><?= form_upload('aanbiedingfoto');?></td>
And my database field is called fotonaam.
I tried something like this, but it did not work:
if($_FILES['aanbiedingfoto']['name'] != '') { $data['fotonaam'] = $_FILES['aanbiedingfoto']['name']; }
What am I doing wrong?
My controller:
function editaanbieding()
{
$data = array(
'Aanbieding' => $this->input->post('aanbiedingnaam'),
'Tekst' => $this->input->post('aanbiedingomschrijving'),
'Prijs' => $this->input->post('aanbiedingprijs'),
'Conditie' => $this->input->post('aanbiedingconditie')
);
if($_FILES['aanbiedingfoto']['name'] != '') { $data['fotonaam'] = $_FILES['aanbiedingfoto']['name']; }
print_r($_FILES);
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['file_name'] = $this->input->post('aanbiedingfoto');
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('aanbiedingfoto'))
{
$error = array('error' => $this->upload->display_errors());
}else{
$image_data = $this->upload->data();
}
$this->aanbieding_model->edit_aanbieding($data, $image_data);
redirect('members/aanbiedingen');
}
My model:
function edit_aanbieding($data, $image_data)
{
$id = $this->uri->segment(3);
$id2 = $this->input->post('fotoid');
$id3 = $this->input->post('aanbiedingid');
/*
echo 'bedrijfaanbiedingid ', $id, '<br/>';
echo 'fotoid ', $id2, '<br/>';
echo 'aanbiedingid ', $id3, '<br/>';
die;
*/
$this->db->where('idaanbiedingen', $id3);
$this->db->update('Aanbiedingen', $data);
$this->db->where('idfotoaanbiedingen', $id2);
$insertfoto = array(
'fotonaam' => $image_data['file_name']
);
$this->db->update('fotoaanbiedingen', $insertfoto);
$this->db->where('idbedrijfaanbiedingen', $id);
}
put your upload code inside the if statement:
<?php
if($_FILES['aanbiedingfoto']['name'] != ''){
if ( ! $this->upload->do_upload('aanbiedingfoto')){
$error = array('error' => $this->upload->display_errors());
}else{
$image_data = $this->upload->data();
}
$this->aanbieding_model->edit_aanbieding($data, $image_data, true);
}else{
$this->aanbieding_model->edit_aanbieding($data, $image_data, false);
}
?>
This is the edit function
<?php
function edit_aanbieding($data, $image_data, $uploaded = false){
$id = $this->uri->segment(3);
$id2 = $this->input->post('fotoid');
$id3 = $this->input->post('aanbiedingid');
/*
echo 'bedrijfaanbiedingid ', $id, '<br/>';
echo 'fotoid ', $id2, '<br/>';
echo 'aanbiedingid ', $id3, '<br/>';
die;
*/
$this->db->where('idaanbiedingen', $id3);
$this->db->update('Aanbiedingen', $data);
$this->db->where('idfotoaanbiedingen', $id2);
if($uploaded){ //update photo code
$insertfoto = array('fotonaam' => $image_data['file_name']);
$this->db->where('idbedrijfaanbiedingen', $id);
$this->db->update('fotoaanbiedingen', $insertfoto);
}
}
?>
If you don't upload any file, $image_data would be NULL.
While there are better solutions, you can fix this as simple as:
Find this section in your model and change it as below:
if (isset($image_data)) {
$insertfoto = array(
'fotonaam' => $image_data['file_name']
);
$this->db->where(...); // Fill the blank with correct arguments
$this->db->update('fotoaanbiedingen', $insertfoto);
}
Side note:
This is completely optional. To increase the performance and get rid of probable errors, I suggest the following:
Avoid of loading libraries or calling methods when not needed.
Set default value for function arguments.
Just as a Demo:
The Controller:
...
if (! empty($_FILES['aanbiedingfoto']['name'])) {
$data['fotonaam'] = $_FILES['aanbiedingfoto']['name'];
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['file_name'] = $this->input->post('aanbiedingfoto');
$this->load->library('upload', $config);
if ($this->upload->do_upload('aanbiedingfoto')) {
$this->aanbieding_model->edit_aanbieding($data, $this->upload->data());
} else {
$error = array('error' => $this->upload->display_errors());
// If you want to update the table while the uploading failed
$this->aanbieding_model->edit_aanbieding($data);
}
}
...
The Model:
function edit_aanbieding($data, $image_data = NULL)
{
...
if (isset($image_data)) {
$insertfoto = array(
'fotonaam' => $image_data['file_name']
);
$this->db->where(...); // Fill the blank with correct arguments
$this->db->update('fotoaanbiedingen', $insertfoto);
}
...
}
Related
I have a form which accepts some text input fields and a file field (used to upload image and pdf).
My problem is like that, if I did not fill upload image, i get an error. How to make the error become text default by the function or i mean that empty field change with my function $default_jarkom etc?
The Controller is:
public function tambah()
{
//$file = base_url()."assets/file/".$_FILES['berkas']['name'];
$default_jarkom = base_url()."assets/images/img1.jpg";
$default_android = base_url()."assets/images/img2.jpg";
$file_gambar = base_url()."assets/images/".$_FILES['berkas1']['name'];
if (isset($_POST['nama']) || isset($_POST['deskripsi'])) {
$matkul = $_POST['matkul'];
$dosen = $_POST['dosen'];
$nama = $_POST['nama'];
$deskripsi = $_POST['deskripsi'];
$file = $_FILES['berkas']['name'];
$file_gambar;
$check = $this->db->query(
"SELECT * FROM materi
WHERE nama_materi='$nama'
OR deskripsi='$deskripsi';"
);
$msg = false;
if ($check->num_rows()==0){
$id = $this->materi_model->buat_id();
$simpan = $this->materi_model->tambah(
$id,
$matkul = $_POST['matkul'],
$dosen,
$nama = $_POST['nama'],
$deskripsi = $_POST['deskripsi'],
$file = $_FILES['berkas']['name'],
$file_gambar
);
if ($simpan) {
$this->aksi_upload() ;
$this->aksi_upload1() ;
$msg = true;
}
}
echo json_encode($msg);
}
}
public function aksi_upload(){
$config['upload_path'] = './assets/file/';
$config['allowed_types'] = 'gif|jpg|png|pdf|doc';
$config['max_size'] = 10000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('berkas')){
$error = array('error' => $this->upload->display_errors());
//$this->load->view('data_tugas_mhs', $error);
return $error;
}else{
$data = array('upload_data' => $this->upload->data());
//$this->load->view('data_tugas_mhs', $data);
return $data;
}
}
public function aksi_upload1()
{
$image = FALSE; //by default file is not uploaded
$data = array();
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png|pdf|doc';
$config['max_size'] = 10000;
$this->load->library('upload', $config);
$default_jarkom = base_url()."assets/images/img1.jpg";
if ( ! $this->upload->do_upload('berkas1'))
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
First you should upload before inserting to get the proper uploaded filename. You should also check all your posts to see if they are null otherwise errors can occur. And you should either escape your input or use query builder as you had an insecure query.
I've modified your upload function as well to keep things DRY.
public function tambah() {
$default_jarkom = base_url() . "assets/images/img1.jpg";
$default_android = base_url() . "assets/images/img2.jpg";
$msg = false;
if (isset($_POST['nama']) || isset($_POST['deskripsi'])) {
$nama = $_POST['nama'];
$deskripsi = $_POST['deskripsi'];
$matkul = isset($_POST['matkul']) ? $_POST['matkul'] : '';
$dosen = isset($_POST['dosen']) ? $_POST['dosen'] : '';
// insecure! you aren't escaping! using query builder or escape your data!!!
$this->db->where('nama_materi', $nama);
$this->db->or_where('deskripsi', $deskripsi);
if ($this->db->count_all_results('materi')) {
$file = $this->aksi_upload('berkas', $default_jarkom);
$file_gambar = $this->aksi_upload('berkas1', $default_jarkom);
$id = $this->materi_model->buat_id();
if ($this->materi_model->tambah($id, $matkul, $dosen, $nama, $deskripsi, $file, $file_gambar)) {
$msg = true;
}
}
}
echo json_encode($msg);
}
/**
* Upload function
*
* #param string $field
* #param string $default Failed upload, return this
* #return string
*/
public function aksi_upload($field = 'userfile', $default = '') {
$this->load->library('upload');
$config['upload_path'] = './assets/file/';
$config['allowed_types'] = 'gif|jpg|png|pdf|doc';
$config['max_size'] = 10000;
$this->upload->initialize($config, true);
if (!$this->upload->do_upload($field)) {
return $default;
}
return base_url() . "assets/images/" . $this->upload->data('file_name');
}
I have a small issue on this code for the to add a product on my system I am using V_add_pro function, when the image upload part is coming I am facing some issues to validate, so that I used a different function to validate through callback, its not working. the main issue is i am saving the image name only to the database, so how to return the image name only?
public function v_add_pro(){
$this->load->model('B_menu');
$data = array('status' => false, 'msg' => array());
$this->load->library('form_validation');
$this->form_validation->set_rules("pro_name", "name needed", "trim|required");
$this->form_validation->set_rules("pro_price", "price needed", "trim|required");
$this->form_validation->set_rules("pro_desc", "description is needed", "trim|required");
$this->form_validation->set_rules("dropzone", "select an image", "trim|required|callback_validate_image");
$this->form_validation->set_rules("pro_cat", "please select a category","callback_check_default|trim|required");
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if ($this->form_validation->run()) {
$data['status'] = true;
$pro_data = array(
'pname' => $this->input->post('pro_name'),
'pprice' => $this->input->post('pro_price'),
'pdesc' => $this->input->post('pro_desc'),
'pimage' =>$this->input->post('dropzone'),
'catid' => $this->input->post('pro_cat'),
);
$this->B_menu->add($pro_data);
} else {
foreach ($_POST as $key => $value) {
$data['msg'][$key] = form_error($key);
}
}
echo json_encode($data);
}
//to check the selected value for category
function check_default($post_string)
{
return $post_string == '0' ? FALSE : TRUE;
}
//to upload the image to the correct path
public function validate_image() {
$config = array(
'allowed_types'=>'jpg|png|gif',
'upload_path'=> realpath(APPPATH . '../skin/images'),
'max_size'=>1
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('dropzone'))
{
$this->form_validation->set_message('validate_image',$this->upload->display_errors());
} else {
$file_info = $this->upload->data();
$img = $file_info['file_name'];
return $img;
}
}
public function validate_image()
{
/* Start: Image Uploading */
$baseurl = $this->config->base_url();
$profile_photo = "";
$profile_path = '';
$config['upload_path'] = './assets/profile_pictures';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
if (!empty($_FILES))
{
$this->file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$this->file_name = time() . "." . $this->file_ext;
$config['file_name'] = $this->file_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image', FALSE))
{
echo $this->upload->display_errors();
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if ($_FILES['image']['error'] != 4)
{
return false;
}
}
else
{
$profile_photo = $this->file_name;
$profile_path = $baseurl . "assets/profile_pictures";
return $profile_photo;
}
}
/* End: Image Uploading */
To add-ons I am just saving file name as current timestamp thats it. Also return $imagename and also try to echo this
echo $this->upload->display_errors();
I want to make my code dry and I'm new to codeigniter I using $this->db->set($data) so I don't need to duplicate many of this set how cound I prevent $this->db->set($data) to skip in_image if it is empty to set it into db when update is it possible ?
My controller:
$data_arr=array(
'title'=>$this->input->post('txttitle'),
'desc'=>$this->input->post('txtdesc'),
'addr'=>$this->input->post('txtaddr'),
'fbn'=>$this->input->post('txtfbname'),
'fburl'=>$this->input->post('txturl'),
'status'=>$this->input->post('status')
);
if(!empty($_FILES['File']['tmp_name']))
{
$new_file_name=date("mdY")."_".time();
$config['upload_path'] = './assets/images/';
$config['allowed_types']= 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 640;
$config['max_height'] = 420;
$config['file_name'] = $new_file_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('File'))
{
$error = array('error' => $this->upload->display_errors());
$image_arr = array('in_image'=>'error');
}
else
{
$image_arr = array('in_image'=>$this->upload->data('orig_name'));
}
}
else
{
$image_arr = array('in_image'=>'');
}
$data_merge = array_merge($data_arr,$image_arr);
$this->Description_model->update_all($data_merge,$id);
my model
public function update_all($data, $id)
{
if($data['in_image'] != 'error' && empty($data['in_image'])
{
/*
this is where i want to check if in_image is empty than prevent
$this->db->set($data) skip to set in_image
*/
$this->db->set($data)
->where('in_id',$id);
if($this->db->update('tbl_desc'))
{return TRUE;}
else
{return FALSE;}
}
elseif($data['in_image'] != 'error' && $data['in_image'] != ''))
{
}
else
{return FALSE;}
}
Thank in advance
Your post is confusing, but it seems you want to prevent the UPDATE whenever in_image is empty, correct?
$data = array
(
'title' => $this->input->post('txttitle'),
'desc' => $this->input->post('txtdesc'),
'addr' => $this->input->post('txtaddr'),
'fbn' => $this->input->post('txtfbname'),
'fburl' => $this->input->post('txturl'),
'status' => $this->input->post('status')
);
if(!empty($_FILES['File']['tmp_name']))
{
$new_file_name = date("mdY")."_".time();
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 640;
$config['max_height'] = 420;
$config['file_name'] = $new_file_name;
$this->load->library('upload', $config);
if($this->upload->do_upload('File'))
$data['in_image'] = $this->upload->data('orig_name');
}
/*
* Checks if the `in_image` index exists in the array.
* Only if the index exists is when it allows the update to happen.
*/
if(isset($data['in_image']) == TRUE)
$this->Description_model->update_all($data, $id);
Now in your model all you need is:
public function update_all($data, $id)
{
$this->db->where('id', $id)
->update('table_name', $data);
}
In codeigniter, data can be updated mainly 2 way,
$data = array{
'YOUR_COL_1' => 'YOUR_VALUR_1',
'YOUR_COL_2' => 'YOUR_VALUR_2',
};
$this->db->where('id', $id);
$this->db->update('YOUR_TABLE', $data);
OR
$this->db->set('YOUR_COL_1', 'YOUR_VALUR_1');
$this->db->set('YOUR_COL_2', 'YOUR_VALUR_2');//if 2 columns
$this->db->where('id', $id);
$this->db->update('YOUR_TABLE');
Also there is another closing bracket needed in if condition as well as !empty
if($data['in_image'] != 'error' && !empty($data['in_image']))
In this, I want to upload csv files. Validation is not correct but without validation its working.
This is my controller:
public function uploadstatetype()
{
$config['upload_path'] = APPPATH.'/assets/upload/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '5000';
with = ' ';
$replace = '"';
$this->load->library('upload', $config);
$this->load->database();
if ( ! $this->upload->do_upload('file_name'))
{
$error = array('error' => $this->upload->display_errors());
$this->managestate($error);
}
else
{
//Insert file info into database
$data = array('upload_data' => $this->upload->data());
$userfile = $data['upload_data']['file_name'];
$this->load->library('csvreader');
$upload_data = $this->upload->data();
$this->load->library('csvreader');
$file = $upload_data['full_path'];
$file_name = $upload_data['userfile'];
$data = $this->csvreader->parse_file($file);
foreach($data as $row)
{
if(($row['state_id']=='')||($row['state_name']==''))
{
$this->session->set_flashdata('msg_excel','Please check the details in the file, some details are empty.');
redirect(base_url().'admin/businesslocation/managestate');
}
else
{
$results_array = array(
'state_id' => $row['state_id'],
'state_name' => $row['state_name']
);
$this->load->model('admin/businesslocation_model');
$this->businesslocation_model->stateupload($results_array);
$success_message='Successfully Upload!';
$this->session->set_flashdata('success_message',$success_message);
redirect(base_url().'admin/businesslocation/managestate');
}
}
}
}
And this is my model:
function stateupload($results_array)
{
$this->db->insert('cr_state', $results_array);
}
For eg state_id=1 and state_name="kerala". Then insert is working,when condition is not checked. But when if condition is given it's not working.
Change your condition like this and try
if(empty($row['state_id'])||(empty($row['state_name']))){
I am inserting some data into the database in my Codeigniter controller
function addsoothingmemory() {
$config['upload_path'] = './uploads2/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500000';
$config['max_width'] = '100024';
$config['max_height'] = '100768';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('soothing', $error);
} else {
$imagedata = $this->upload->data();
$data = array(
'image_path' => $imagedata['file_name'],
'title' => $this->input->post('title'),
'user_id' => $this->session->userdata("user_id"),
'feelingrate' => $this->session->userdata("feelingrate"),
'description' => $this->input->post('description')
);
$query = $this->favourite_db->getsoothingcount() + 1;
$this->favourite_db->add_soothingmemory($data);
$count = array('soothingcount' => $query);
$this->favourite_db->updateusercount($count);
$this->load->view('positivepast', $data);
}
}
Model
function add_soothingmemory($data) {
$this->load->database();
$this->db->insert('soothingmemory', $data);
$this->set_session();
return $data;
}
The problem is when the value is inserted into the database it inserts three times creating multiple/duplicate rows.
I had the same problem,
anyhow, in your model,
$this->db->limit(1);
$this->db->insert('soothingmemory', $data);
that way duplicates will be avoided.
Hope it helps
Make the following changes:
function addsoothingmemory() {
$config['upload_path'] = './uploads2/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500000';
$config['max_width'] = '100024';
$config['max_height'] = '100768';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('soothing', $error);
} else {
$imagedata = $this->upload->data();
$data = array(
'image_path' => $imagedata['file_name'],
'title' => $this->input->post('title'),
'user_id' => $this->session->userdata("user_id"),
'feelingrate' => $this->session->userdata("feelingrate"),
'description' => $this->input->post('description')
);
$query = $this->favourite_db->getsoothingcount() + 1;
$save = $this->favourite_db->add_soothingmemory($data);
// Move this code into the model
// $count = array('soothingcount' => $query);
if($save == true){
$this->favourite_db->updateusercount($query);
$this->load->view('positivepast', $data);
}else{
//do something else
}
}
}
In the model
function add_soothingmemory($data) {
$this->load->database();
$save = $this->db->insert('soothingmemory', $data);
//This condition will check, if the $data was save
if($save == true){
//If is save, it will set the session and return true
$this->set_session();
return true;
}else{
return false;
}
}