When I submit my form on my main index I am trying to pass a variable call $store_id to a function on same controller called do_upload_image($store_id)
I am trying to be able to get the last id that was inserted in my store table.
It works fine when loading another model function $this->example_model->add($store_id); but not when doing it on another function on same controller.
Error Output
Column 'store_id' cannot be null
INSERT INTO `setting` (`store_id`, `group`, `key`, `value`) VALUES (NULL, 'config', 'config_image', 'flagnz.png')
Like so
$store_id = $this->model_store_add->add_store(); // this way should let me get id that was inserted.
$this->do_upload_image($store_id);
How am I able to get the $store_id to pass through another function on same controller? I have a model which trying to pass the store id to on do_upload_image
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Store_add extends MX_Controller {
public $store_id;
public function __construct() {
parent::__construct();
if (!$this->session->userdata('isLogged')) {
redirect('admin');
}
$this->load->model('admin/setting/model_store_add');
$this->load->model('admin/setting/model_store_get');
$this->lang->load('admin/setting/store_add', $this->settings->get('config_admin_language'));
}
public function index()
$this->load->library('form_validation');
$this->form_validation->set_rules('config_image', 'Store Image','callback_do_upload_image');
if ($this->form_validation->run($this) == FALSE) {
return $this->load->view('setting/store_add.tpl');
} else {
// $store id lets me get id that was inserted from store table
$store_id = $this->model_store_add->add_store();
$this->model_store_add->add_config_meta_title($store_id); // Works
$this->do_upload_image($store_id);
$this->session->set_flashdata('success', $this->lang->line('text_success'));
redirect('admin/setting/store');
}
}
public function do_upload_image($store_id) {
$config['upload_path'] = './image/upload/';
$config['allowed_types'] = $this->settings->get('config_file_ext_allowed');
$config['max_size'] = $this->settings->get('config_file_max_size');
$config['overwrite'] = $this->settings->get('config_file_overwrite');
$config['max_width'] = '*';
$config['max_height'] = '*';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (is_uploaded_file($_FILES['config_image']['tmp_name'])) {
if (!$this->upload->do_upload('config_image')) {
$this->form_validation->set_message('do_upload_image', $this->upload->display_errors('<b>config_image</b>' .' '));
return false;
} else {
$resize_data = $this->upload->data();
$config_resize['image_library'] = 'gd2';
$config_resize['source_image'] = './image/upload/' . $resize_data['file_name'];
$config_resize['new_image'] = './image/cache/' . $resize_data['file_name'];
$config_resize['maintain_ratio'] = false;
$config_resize['create_thumb'] = false;
$config_resize['width'] = 100;
$config_resize['height'] = 100;
$this->load->library('image_lib', $config_resize);
$this->image_lib->initialize($config_resize);
if (!$this->image_lib->resize()) {
$this->sessions->set_flashdata('error', $this->image_lib->display_errors());
redirect('admin/setting/setting');
} else {
$this->model_store_add->add_config_image($store_id, $this->upload->data());
}
}
}
}
}
Model on do_upload_image
public function add_config_image($store_id = 0, $file_data = array()) {
$file_data = $this->upload->data();
$data = array(
'store_id' => $store_id,
'group' => "config",
'key' => "config_image",
'value' => $file_data['file_name']
);
$this->db->set($data);
$this->db->insert($this->db->dbprefix. 'setting');
}
Model add
public function add_store() {
$data = array(
'name' => $this->input->post('config_name'),
'url' => $this->input->post('config_url'),
'ssl' => $this->input->post('config_ssl')
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'store');
return $this->db->insert_id();
}
I have narrowed down my own problem. I need to pass the store id a second time as a if statement and now all works
I just removed the resize function for testing to see if that was issue but now no why. Also need to add return true below for callback function.
public function do_upload_image($store_id) {
$config['upload_path'] = './image/upload/';
$config['allowed_types'] = $this->settings->get('config_file_ext_allowed');
$config['max_size'] = $this->settings->get('config_file_max_size');
$config['overwrite'] = $this->settings->get('config_file_overwrite');
$config['max_width'] = '*';
$config['max_height'] = '*';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('config_image')) {
if ($store_id) {
$this->model_store_add->add_config_image($store_id, $this->upload->data());
}
return true;
} else {
return false;
}
}
Related
I am new to codeigniter and I am having problem in edit item image, not that it don't get update as it do but there are too many images in the upload folder directory.
What I want to do is I want the previously stored image to be deleted in the upload directory when I update new image.
Here is my controller:
function edit($shop_id = null){
if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
/* Breadcrumbs */
$this->data['breadcrumb'] = $this->breadcrumbs->show();
/* Variables */
$tables = $this->config->item('tables', 'ion_auth');
$this->data['shop_id'] = $shop_id;
/* Get all category */
$this->data['shopInfo'] = $this->shop_model->getShopInfo($shop_id);
//echo "<pre>";print_r( $this->data['shopInfo']);echo "</pre>";exit;
/* Validate form input */
$this->form_validation->set_rules('shop_name', 'Shop Name', 'trim|required');
$this->form_validation->set_rules('shop_latidude', 'Shop Latidude', 'trim|required');
$this->form_validation->set_rules('shop_longitude', 'Shop Longitude', 'trim|required');
if($this->form_validation->run() == true) {
$config['upload_path'] = './assets/uploads/shop/';
//die(var_dump(is_dir($config['upload_path'])));
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
$img_upload = $this->upload->do_upload($img);
$data = $this->upload->data();
$file = array('file_name' => $data['file_name'] );
$data = array('upload_data' => $this->upload->data());
$photo = base_url().'assets/uploads/shop/'.$file['file_name'];
if($img_upload == 1 ) $post_photo = $photo;
else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
$shopInfo = array(
'shop_name' => $this->input->post('shop_name'),
'merchant_id' => $this->input->post('merchant_id'),
'photo' => $post_photo,
'description' => $this->input->post('shop_desc'),
'registered_date'=> date('Y-m-d H:i:s'),
'is_active' => 1,
'shop_location' => $this->input->post('shop_loc'),
'shop_address' => $this->input->post('shop_add'),
'shop_phone' => $this->input->post('shop_ph'),
'shop_latitude' => $this->input->post('shop_latidude'),
'shop_longitude'=> $this->input->post('shop_longitude'),
'open_hour' => $this->input->post('open_hour'),
'close_hour' => $this->input->post('close_hour'),
'remark' => $this->input->post('remark'),
'approved' => $status
);
$this->shop_model->shopUpdate($shop_id, $shopInfo);
redirect(base_url() . 'admin/shop', 'refresh');
} else {
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
/* Load Template */
$this->data['merchant'] = $this->merchant_model->getAllMerchants();
$this->template->admin_render("admin/shop/edit", $this->data);
}
}
Here is my Model:
function shopUpdate($shop_id, $shopInfo) {
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
function shopUpdate($shop_id, $shopInfo) {
$q = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
if ($q->num_rows() > 0) {
$imgName = $q->row();
// image path must be './admin/shop'
unlink("./{image pathe}/".$imgName);
}
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
you got file name when image got uploaded so get the file name where you are going to update and delete file first. Use unlink to delete file. run update query.
you just need to change in model for updating and deleting at same time.
First, check if new image uploading or not
$new_image = $_FILES['userfile']['name'] ? $_FILES['userfile']['name'] : '';
if($new_image != ''){
$old_image = $this->shop_model->getOlgImage($shop_id);
if(isset($old_image) && file_exists('image-path/photo.jpg')){
unlink('image-path/image');
}
}
Old image is now deleted. Upload new
$config['upload_path'] = './assets/uploads/shop/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
Give name of your input type file name to $this->upload->do_upload() not variable
No need to add $this->upload->data() twice
if($this->upload->do_upload('userfile')){
$data = $this->upload->data();
$photo = base_url().'assets/uploads/shop/'.$data['file_name'];
$post_photo = $photo;
} else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
Get old image
public function getOldImage($shop_id){
return $this->db->get_where('shop', ['shop_id' => $shop_id])->row()->photo;
}
First, you need to get image name from the database by ID then update record. Once the record is updated then you can delete that image the folder directory.
function shopUpdate($shop_id, $shopInfo) {
//fetch image name from the database by shop_id
$imageName = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
//record is updated successfully now delete that image from folder
if ($imageName->num_rows() > 0) {
unlink("./{image pathe}/".$imageName->row());
}
return true;
} else {
return false;
}
} else {
return false;
}
}
unlink()
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;
}
}
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);
}
...
}