trying to add upload image in my form CI MySQL - php

I have form for input. Input for this form is quite complicated, because one form is submitted to more than three table in database. I want to add upload image in my form, but I don't know where should I put it. here's my controller for input
function c_submit(){
$data = array(
'no_form' => $this->input->post('noform'),
'no_kon' => $this->input->post('nokon'),
'tgl_kun' => $this->input->post('tk'),
'tgl_input' => date("Y-m-d H:i:s"),
'no_lok' => $this->input->post('nolok'),
'no_obs' => $this->input->post('noobs'),
'no_koor' => $this->input->post('nokoor'),
'no_lahan' => $this->input->post('nolahan'),
't_utama' => $this->input->post('tutama'),
'pola_t' => $this->input->post('ptanam'),
'dlm_olah' => $this->input->post('kolah'),
't_tanah' => $this->input->post('ttanah'),
'no_prod' => $this->input->post('noprod'),
'np_padi' => $this->input->post('nppadi'),
'np_jagung' => $this->input->post('npjagung'),
'np_kedelai' => $this->input->post('npked'),
'np_lain' => $this->input->post('nplain'),
'catatan' => $this->input->post('cat')
);
$datakon = array(
'no_kon' => $this->input->post('nokon'),
'jabatan' => $this->input->post('jab'),
'nama' => $this->input->post('namakon'),
'telp' => $this->input->post('telp')
);
$datakoor = array(
'no_koor' => $this->input->post('nokoor'),
'utm_y' => $this->input->post('y'),
'utm_x' => $this->input->post('x')
);
$datalahan = array(
'no_lahan' => $this->input->post('nolahan'),
'jenis' => $this->input->post('jlahan'),
'penggunaan' => $this->input->post('plahan'),
'kondisi' => $this->input->post('klahan'),
'drainase' => $this->input->post('drain')
);
$dataprod = array(
'no_prod' => $this->input->post('noprod'),
'p_padi' => $this->input->post('p_padi'),
'p_jagung' => $this->input->post('p_jagung'),
'p_kedelai' => $this->input->post('p_ked'),
'pr_lain' => $this->input->post('pr_lain'),
'prod_lain' => $this->input->post('prod_lain'),
'pr_lain2' => $this->input->post('pr_lain2'),
'prod_lain2' => $this->input->post('prod_lain2')
);
$datavar = array(
'no_var' => $this->input->post('novar'),
'v_padi' => $this->input->post('v_padi'),
'v_jagung' => $this->input->post('v_jagung'),
'v_kedelai' => $this->input->post('v_ked'),
'v_lain' => $this->input->post('v_lain'),
'var_lain' => $this->input->post('var_lain'),
'v_lain2' => $this->input->post('v_lain2'),
'var_lain2' => $this->input->post('var_lain2')
);
$datalok = array(
'no_lok' => $this->input->post('nolok'),
'kabu' => $this->input->post('kabu'),
'keca' => $this->input->post('keca'),
'desa' => $this->input->post('desa'),
'desk' => $this->input->post('desk_lok')
);
$datappadi = array(
'np_padi' => $this->input->post('nppadi'),
'p_organik' => $this->input->post('padi_o'),
'p_urea' => $this->input->post('padi_u'),
'p_kcl' => $this->input->post('padi_k'),
'p_sp36' => $this->input->post('padi_s'),
'p_phonska' => $this->input->post('padi_p'),
'p_lain' => $this->input->post('pp_l'),
'pp_lain' => $this->input->post('padi_l')
);
$datapjagung = array(
'np_jagung' => $this->input->post('npjagung'),
'j_organik' => $this->input->post('jagung_o'),
'j_urea' => $this->input->post('jagung_u'),
'j_kcl' => $this->input->post('jagung_k'),
'j_sp36' => $this->input->post('jagung_s'),
'j_phonska' => $this->input->post('jagung_p'),
'j_lain' => $this->input->post('pj_l'),
'pj_lain' => $this->input->post('jagung_l')
);
$datapked = array(
'np_kedelai' => $this->input->post('npked'),
'k_organik' => $this->input->post('ked_o'),
'k_urea' => $this->input->post('ked_u'),
'k_kcl' => $this->input->post('ked_k'),
'k_sp36' => $this->input->post('ked_s'),
'k_phonska' => $this->input->post('ked_p'),
'k_lain' => $this->input->post('pk_l'),
'pk_lain' => $this->input->post('ked_l')
);
$dataplain = array(
'np_lain' => $this->input->post('nplain'),
'jenis_l' => $this->input->post('j_lain'),
'organik' => $this->input->post('lain_o'),
'urea' => $this->input->post('lain_u'),
'kcl' => $this->input->post('lain_k'),
'sp36' => $this->input->post('lain_s'),
'phonska' => $this->input->post('lain_p'),
'pupuk_lain' => $this->input->post('pl_l'),
'pem_lain' => $this->input->post('lain_l')
);
$no_obs = $this->session->userdata('no_obs');
$this->m_input->m_submit($data, $datakon, $datakoor, $datalahan, $dataprod, $datavar, $datalok, $datappadi, $datapjagung, $datapked, $dataplain);
$this->session->set_flashdata('msg', '<div class="alert alert-success"><p><b>SUKSES!</b> Data berhasil diinputkan!</p></div>');
redirect('c_read');
}
and this my model
function m_submit($data, $datakon, $datakoor, $datalahan, $dataprod, $datavar, $datalok, $datappadi, $datapjagung, $datapked, $dataplain) {
$this->db->trans_start();
$this->db->insert('koor_pen', $datakoor);
$no_koor = $this->db->insert_id();
$this->db->insert('kontak', $datakon);
$no_kon = $this->db->insert_id();
$this->db->insert('lahan', $datalahan);
$no_lahan = $this->db->insert_id();
$this->db->insert('produktivitas', $dataprod);
$no_prod = $this->db->insert_id();
$this->db->insert('varietas', $datavar);
$no_var = $this->db->insert_id();
$this->db->insert('lokasi', $datalok);
$no_lok = $this->db->insert_id();
$this->db->insert('pem_padi', $datappadi);
$np_padi = $this->db->insert_id();
$this->db->insert('pem_jagung', $datapjagung);
$np_jagung = $this->db->insert_id();
$this->db->insert('pem_kedelai', $datapked);
$np_kedelai = $this->db->insert_id();
$this->db->insert('pem_lain', $dataplain);
$np_lain = $this->db->insert_id();
$data['no_kon'] = $no_kon;
$data['no_koor'] = $no_koor;
$data['no_lahan'] = $no_lahan;
$data['no_prod'] = $no_prod;
$data['no_var'] = $no_var;
$data['no_lok'] = $no_lok;
$data['np_padi'] = $np_padi;
$data['np_jagung'] = $np_jagung;
$data['np_kedelai'] = $np_kedelai;
$data['np_lain'] = $np_lain;
$this->db->insert('input_pen', $data);
$this->db->trans_complete();
return $this->db->insert_id();
}
Link for my uploaded image should in $data array. I don't know what should I do. Can anyone give me examples?

First lets clear the code
for submit sevral forms you can easily user array in html name tag
<input name="datakon[no_kon]" >
<input name="datakon[jab]" >
<input name="datakon[namakon]" >
<input name="datakon[telp]" >
And in Controller side you insert them into database in one line
$datakon = $this->input->post('datakon');
$this->db->insert('kontak', $datakon);
$no_kon = $this->db->insert_id();
And if your database table name was same as your input fields, its done
Now lets to start uploading files
You should not Upload files in database.
instead of uploading file to database you can uplade files to a directory and save that directory address.
for uploading files you can use codeigniter upload library Codeigniter Upload File Documentation
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('no_kon'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
Hope to help

This script will upload your file in destination folder mkdir($config['upload_path'], 0777, TRUE);
Param number 3, TRUE will create recursively the directory for you.
And the corresponding line will place a name and path to database
$post_data = array(
'name' => $_FILES["__INPUT__FIELD__NAME"]['name'],
'path' => $hook
);
$this->db->insert('FILES__DB__', $post_data);
Generall usage
File_handler model
<?PHP
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class File_handler extends CI_Model {
private $base_p = "./files/";
private $ext = 'pdf|csv|doc|txt';
private $size = 5000000;
function _push_file($path, $name) {
// make sure it's a file before doing anything!
if (is_file($path)) {
// required for IE
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
// get the file mime type using the file extension
$this->load->helper('file');
$mime = get_mime_by_extension($path);
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Cache-Control: private', false);
header('Content-Type: ' . $mime); // Add the mime type from Code igniter.
header('Content-Disposition: attachment; filename="' . basename($name) . '"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($path)); // provide file size
header('Connection: close');
readfile($path); // push it out
exit();
}
}
public function fsize($s) {
$this->size = $s;
}
public function fext($ext) {
$this->ext = $ext;
}
public function upload_file($field, $subpath) {
if (!empty($_FILES[$field]['name'])) {
$config['upload_path'] = $this->base_p . '' . $subpath;
$config['allowed_types'] = $this->ext;
$config['max_size'] = $this->size; // 5 mb
$config['encrypt_name'] = TRUE;
if (!is_dir($config['upload_path'])) {
mkdir($config['upload_path'], 0777, TRUE);
}
$this->load->library('upload', $config);
if (!$this->upload->do_upload($field)) {
$status = 'error';
$msg = $this->upload->display_errors('', '');
return json_encode(array('result' => 'error', 'msg' => $msg));
die();
} else {
$data = $this->upload->data();
}
return $path = 'files' . $subpath . '/' . $data['file_name'];
}
}
}
Use this in your logic model
$this->load->model("File_handler", "fh");
$this->fh->fext("jpg|jpeg|pdf|png");
$hook = $this->fh->upload_file("__INPUT__FIELD__NAME", "__PATH__TO__UPLOAD");
// Errors from File_handler controller
if (isset(json_decode($hook)->result) && json_decode($hook)->result == "error") {
$message = json_decode($hook)->msg;
}
// If we got the path all is ok
if ($hook) {
$post_data = array(
'name' => $_FILES["__INPUT__FIELD__NAME"]['name'],
'path' => $hook
);
$this->db->insert('FILES__DB__', $post_data);
$fid = $this->db->insert_id();
if (!is_numeric($fid)) {
$message = "Error, file not added";
}
}
if (strlen($message) == 0) {
// No errors in the file handler
// get your upload url path with file name from $hook
}else{
echo $message;
}.
In your case :
You will need to create a table in your database use this schema
CREATE TABLE `file_uploads` (
`id` bigint(20) NOT NULL,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`time_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`path` varchar(200) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Indexes
--
ALTER TABLE `file_uploads`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT
--
ALTER TABLE `file_uploads`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;COMMIT;
Your model
function m_submit($data, $datakon, $datakoor, $datalahan, $dataprod, $datavar, $datalok, $datappadi, $datapjagung, $datapked, $dataplain) {
$this->db->trans_start();
$this->db->insert('koor_pen', $datakoor);
$no_koor = $this->db->insert_id();
$this->db->insert('kontak', $datakon);
$no_kon = $this->db->insert_id();
$this->db->insert('lahan', $datalahan);
$no_lahan = $this->db->insert_id();
$this->db->insert('produktivitas', $dataprod);
$no_prod = $this->db->insert_id();
$this->db->insert('varietas', $datavar);
$no_var = $this->db->insert_id();
$this->db->insert('lokasi', $datalok);
$no_lok = $this->db->insert_id();
$this->db->insert('pem_padi', $datappadi);
$np_padi = $this->db->insert_id();
$this->db->insert('pem_jagung', $datapjagung);
$np_jagung = $this->db->insert_id();
$this->db->insert('pem_kedelai', $datapked);
$np_kedelai = $this->db->insert_id();
$this->db->insert('pem_lain', $dataplain);
$np_lain = $this->db->insert_id();
$data['no_kon'] = $no_kon;
$data['no_koor'] = $no_koor;
$data['no_lahan'] = $no_lahan;
$data['no_prod'] = $no_prod;
$data['no_var'] = $no_var;
$data['no_lok'] = $no_lok;
$data['np_padi'] = $np_padi;
$data['np_jagung'] = $np_jagung;
$data['np_kedelai'] = $np_kedelai;
$data['np_lain'] = $np_lain;
$this->db->insert('input_pen', $data);
/* add my image */
$this->load->model("File_handler", "fh");
$this->fh->fext("jpg|jpeg|pdf|png");
$hook = $this->fh->upload_file("__INPUT__FIELD__NAME", "__PATH__TO__UPLOAD");
// Errors from File_handler controller
if (isset(json_decode($hook)->result) && json_decode($hook)->result == "error") {
$message = json_decode($hook)->msg;
}
// If we got the path all is ok
if ($hook) {
$post_data = array(
'name' => $_FILES["foto"]['name'],
'path' => $hook
);
$this->db->insert('file_uploads', $post_data);
$fid = $this->db->insert_id();
if (!is_numeric($fid)) {
$message = "Error, file not added";
}
}
if (strlen($message) == 0) {
// No errors in the file handler
// get your upload url path with file name from $hook and do here whatever u want
} else {
echo $message;
}
$this->db->trans_complete();
return $this->db->insert_id();
}
Things to be noticed HTML
You need to have your form enctype="multipart/form-data"
<form id="FormId" name="Formname" method="post" enctype="multipart/form-data" accept-charset="utf-8">
And the input type file
<input type="file" class="form-control" name="foto" id="foto">
Code sample for jquery ajax handling
$.ajax({
url: '<?PHP echo base_url(); ?>CONTROLLER/FUNCTION',
type: "POST",
mimeType: "multipart/form-data",
contentType: false,
dataType: 'json',
cache: false,
processData: false,
data: $form.serialize(),
success: function (data) {
// Your logic
}
});

Related

Codeigniter 4 Multiple Image Upload Issue

When I update the database, it uploads a single image. How do I upload multiple?
$id = $this->request->getPost('id');
$model = new UrunModel();
$file = $this->request->getFile('resim');
$resim_eski = $model->find($id);
if($file->isValid() && !$file->hasMoved()){
$eski_resim = $resim_eski['resim'];
if(file_exists("dosyalar/uploads".$eski_resim)){
unlink("dosyalar/uploads".$eski_resim);
}
$imagename = $file->getRandomName();
$file->move("dosyalar/uploads", $imagename);
}else{
$imagename = $resim_eski['resim'];
}
if ($this->request->getFileMultiple('images')) {
foreach($this->request->getFileMultiple('images') as $res)
{
$res->move(WRITEPATH . 'dosyalar/uploads');
$data=[
'baslik' => $this->request->getPost('baslik'),
'slug' => mb_url_title($this->request->getPost('baslik'), '-', TRUE),
'kisa_aciklama' => $this->request->getPost('kisa_aciklama'),
'kategori' => $this->request->getPost('kategori'),
'query_kategori' => $this->request->getPost('query_kategori'),
'aciklama' => $this->request->getPost('aciklama'),
'fiyat' => $this->request->getPost('fiyat'),
'indirimli_fiyat' => $this->request->getPost('indirimli_fiyat'),
'resim' => $imagename,
'resimler' => $res->getClientName(),
'type' => $res->getClientMimeType()
];
$model -> update($id,$data);
}
}
return redirect()->to(base_url('yonetim/urunler'));
}
Controller code above, I've been struggling for 2 days, I couldn't manage it somehow.
When I run the code, it just adds 1 image to each product. I want to add more than one image to 1 product for the gallery part. Any suggestions for this code or a different solution?
function add()
{
$length = count($_FILES['image']['name']);
$filename = $_FILES['image']['name'];
$tempname = $_FILES['image']['tmp_name'];
$allimage = array();
foreach($filename as $key =>$value)
{
move_uploaded_file($tempname[$key],'media/uploads/mobile_product/'.$filename[$key]);
$allimage[] = $filename[$key];
}
if(!empty($allimage))
{
$allimage = json_encode($allimage);
}
else
{
$allimage = '';
}
$data['image'] = $allimage;
$this->db->insert('table',$data);
}
CI4 Controller:
if($this->request->getFileMultiple('image_files')) {
$files = $this->request->getFileMultiple('image_files');
foreach ($files as $file) {
if ($file->isValid() && ! $file->hasMoved())
{
$newNames = $file->getRandomName();
$imageFiles = array(
'filename' => $newNames
);
$modelName->insert($imageFiles );
$file->move('uploads/', $newNames);
}
}
}
HTML
<input type="file" name="image_files[]">
This is the shortest way to do that

Error submitting a form with upload pic option. PHP Codeigniter

I've been trying to upload a pic to a folder and store its path in the database, my code seems to work correctly, but no it's not, After i click submit button, it goes to a blank page.
Using Inspect element, Network option in my browser, when seeing the parameters sent
I see correct input from the text fields but for the image,
Content-Disposition: form-data; name="myimage"; filename="IMG_8971.JPG"
Content-Type: image/jpeg
Plus some other weirly looking characters and symbols like :
ÿØÿà
CONTROLLER:
private function setup_upload_option()
{
$config = array();
$config['upload_path'] = 'blog/uploads/';
$config['allowed_type']='jpg|jpeg|png|gif';
$config['encrypt_name']= TRUE;
$config['overwrite']=FALSE;
return $config;
}
public function post_new_blog()
{
$this->form_validation->set_rules('title', 'Title of the Blog', 'trim|required');
$this->form_validation->set_rules('desc', 'Content of the Blog', 'trim|required');
$this->form_validation->set_rules('tags', 'Tags fo the blog', 'trim|required');
if($this->form_validation->run()==FALSE) {
$this->session->set_flashdata('fail', validation_errors());
$this->load->view('blogsection/addblog', array('logged_in' => $this->logged_in));
}
else {
$this->load->library('upload');
$files = $_FILES;
$count = count($_FILES['myimage']['name']);
for($i=0; $i<$count ;$i++)
{
$_FILES['myimage']['name'] = $files['myimage']['name'][$i];
$_FILES['myimage']['type'] = $files['myimage']['type'][$i];
$_FILES['myimage']['size'] = $files['myimage']['size'][$i];
$_FILES['myimage']['tmp_name'] = $files['myimage']['tmp_name'][$i];
$this->upload->initialize($this->setup_upload_option());
if($this->upload->do_upload()==TRUE)
{
$data = $this->upload->data();
$config1['image_library'] = 'gd2';
$config1['source_image'] = $data['full_path'];
$config1['new_image'] = 'blog/uploads/thumbs/';
$config1['create_thumb'] = false;
$config1['height'] = 200;
$config['width'] = 200;
$this->load->library('image_lib', $config1);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$mydata = $this->session->all_userdata();
$dataarray = array(
'blog_title' => $this->input->post('title', true),
'blog_content' => $this->input->post('desc', true),
'blog_tags' => $this->input->post('tags', true),
'blog_image_name' => $data['orig_name'],
'blog_image' => $data['full_path'],
'date_posted' => date(" jS \of F Y "),
'posted_by' => $mydata['username']
);
$this->main_model->save_new_posts($dataarray);
$this->load->view('blogsection/addblog', array('logged_in' => $this->logged_in, 'success' => 'Blog was posted successfully',$dataarray));
}
}
}
}
MODEL:
public function save_new_posts($dataarray)
{
$this->db->insert('blogs', $dataarray);
if($this->db->affected_rows()>0)
{
return true;
}
}
i have code that always works, it is some what different from you method i hope it will help you.
$imgpath='uploads/profile_pic/';
$all_img="";
if($_FILES["profile_pic"]['name'])//form input type file
{
$path_parts = pathinfo($_FILES["profile_pic"]["name"]);
$image_path = $path_parts['filename'].'_'.time().'.'.$path_parts['extension'];
$all_img.=$image_path;
move_uploaded_file($file_tmp=$_FILES["profile_pic"]["tmp_name"],$imgpath."/".$image_path);
$data['cm_user_profile_pic']=$all_img;//store image name in array
}

getting file name as null by using var_dump

I have created file uploading function using ajax and codeigniter the problem is that when I am trying to upload an image it is working fine but when I try to upload document or excel file it is giving me null can anybody help me out to fix this issue
here is what error I am getting Array ( [error] => The filetype you are attempting to upload is not allowed.)
Here is my controller
public function post_forum() {
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png|doc|docx|xls|xlsx|pdf';
$this->load->library('upload', $config);
if(!empty($_FILES['post_image']['name'])) {
if (!$this->upload->do_upload('post_image')) {
$error = array('error' => $this->upload->display_errors());
} else {
$dt = $this->upload->data();
$file = $dt['file_name'];
}
} else {
$file = '';
}
$word_dta = $this->input->post('post_dt');
$time_posted = time();
$user_id = $this->basic_model->is_login($this);
empty($this->input->post('group_id')) ? $group_id = '' : $group_id = $this->input->post('group_id');
empty($this->input->post('c_id')) ? $company_id = '' : $company_id = $this->input->post('c_id');
$data_upload = array(
'upload_document' => $file,
'discussion' => $word_dta,
'user_id' => $user_id,
'group_id' => $group_id,
'company_id' => $company_id,
'time_posted' => $time_posted,
'status' => 'Posted'
);
$post_id = $this->basic_model->insertRecord($data_upload, 'forums');
$data = array(
'file_name' => $file,
'data' => $word_dta,
'time_posted' => $time_posted,
'post_id' => $post_id,
'name' => $this->basic_model->getUserData(),
'command' => 'Submit Post'
);
$this->load->view('forum/includes/get_data', $data);
}
This is my html form which I have created in views folder
<form method="POST" action="" id="postform" enctype="multipart/form-data" onsubmit="return false;">
<input type="file" id="imageFieldId" name="post_image" />
<div id="contentbox" contenteditable="true" name="post_dt">
</div>
<input type="submit" id="sb_art" class="btn_v2" value="Start Discussion" />
</form>
This is my ajax call
$(document).ready(function(e) {
$("#postform").on('submit', (function(e) {
$("#load").show();
var form = this;
var formData = new FormData(this);
formData.append('post_dt', $("#contentbox").html());
$.ajax({
url : "http://tfsquare.com/demo/forums/post_forum",
type : "POST",
data : formData,
contentType : false,
cache : false,
processData : false,
success : function(data) {
$("#data_update").prepend($(data).fadeIn('slow'));
$("#contentbox").empty();
$('.no_st').css('display', 'none');
form.reset();
},
complete: function() {
$("#load").hide();
}
});
}));
});
$config['allowed_types'] = 'gif|jpg|png|doc|docx|xls|xlsx|pdf';
Codeigniter validate files not only with their extension but also with their MIME type. Probably Your given excel files doesn't have the mime entries in your Mimes.php which is located in config.php.
If you can find the content type add add it to the mime array in mimes.php. If not manually validate the extension by exploding the file name and Do not use codeigniter's 'allowed_types'.
Try this
if(!empty($_FILES['post_image']['name'])) {
if (!$this->upload->do_upload('post_image')) {
$error = array('error' => $this->upload->display_errors());
} else {
$ext = ['xls', 'xlsx'];
$dt = $this->upload->data();
$file = $dt['file_name'];
if( in_array($dt['file_ext'], $ext){
echo 'Valid File';
}
}
} else {
$file = '';
}

how to import csv file to MYSQL in codeigniter which contain html tags

I want to import csv into mysql using codeigniter.
This is my source code.
I have an unnormalized events-diary CSV from a client that I'm trying to load into a MySQL table so that I can refactor into a sane format.
I created a table called 'CSVImport' that has one field for every column of the CSV file
function import_questions(){
$question_type=$_POST['question_type'];
$main_category_name=$_POST['main_category_name'];
$sub_category_name=$_POST['sub_category_name'];
$exam_name_list=$_POST['exam_name_list'];
$chapter_name=$_POST['chapter_name'];
$lesson_name=$_POST['lesson_name'];
$difficult_level=$_POST['difficult_level'];
$input_type=$_POST['input_type'];
$config = array();
$config['upload_path'] = './uploads/question_upload/';
$config['allowed_types'] = '*';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$this->load->library('upload',$config);
$tb_name=$_FILES['userfile']['name'];
$tb_type=$_FILES['userfile']['type'];
if (!$this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('failure', 'File Uploaded Error!.');
header('Location:'.$this->data['base'].'cbulkupload/');
}
else
{
$datas = array('upload_data' => $this->upload->data());
$filename = $datas['upload_data']['full_path'];
require_once './excel/excel_reader2.php';
if($tb_type == 'application/vnd.ms-excel')
{
$data = new Spreadsheet_Excel_Reader($filename);
for($i=0;$i<=count($data->sheets);$i++) // Loop to get all sheets in a file.
{
//echo "count :".count($data->sheets);
//echo "<pre>";print_r($data->sheets[$i][cells]);
if(count($data->sheets[$i][cells])>0) // checking sheet not empty
{
for($j=1;$j<=count($data->sheets[$i][cells]);$j++) // loop used to get each row of the sheet
{
//echo "<pre>";print_r($data->sheets[$i][cells][$j]);
if($j != 1){
$QUESTION_AREA = mysql_real_escape_string(preg_replace("/\s+/"," ",$data->sheets[$i][cells][$j][1]));
$TEXT_OPTION1 = mysql_real_escape_string(preg_replace("/\s+/"," ",$data->sheets[$i][cells][$j][2]));
$TEXT_OPTION2 = mysql_real_escape_string(preg_replace("/\s+/"," ",$data->sheets[$i][cells][$j][3]));
$TEXT_OPTION3 = mysql_real_escape_string(preg_replace("/\s+/"," ",$data->sheets[$i][cells][$j][4]));
$TEXT_OPTION4 = mysql_real_escape_string(preg_replace("/\s+/"," ",$data->sheets[$i][cells][$j][5]));
$TEXT_OPTION5 = mysql_real_escape_string(preg_replace("/\s+/"," ",$data->sheets[$i][cells][$j][6]));
$RESULT_OPTION = $data->sheets[$i][cells][$j][7];
$ANSWER_DESCRIPTION = mysql_real_escape_string(preg_replace("/\s+/"," ",$data->sheets[$i][cells][$j][8]));
$query = "insert into add_question(MAIN_CATEGORY_ID,SUB_CATEGORY_ID,EXAM_NAME_ID,CHAPTER_ID,LESSON_ID,INPUT_TYPE,DIFFICULT_LEVEL,DIAGNOSIS_VALUE,CREATED_DATE,ACTIVE_STATUS,QUESTION_AREA,TEXT_OPTION1,TEXT_OPTION2,TEXT_OPTION3,TEXT_OPTION4,TEXT_OPTION5,RESULT_OPTION,ANSWER_DESCRIPTION) values(
'".$main_category_name."','".$sub_category_name."','".$exam_name_list."','".$chapter_name."','".$lesson_name."','".$input_type."','".$difficult_level."','".$question_type."',NOW(),'Y','".$QUESTION_AREA."','".$TEXT_OPTION1."','".$TEXT_OPTION2."','".$TEXT_OPTION3."','".$TEXT_OPTION4."','".$TEXT_OPTION5."','".$RESULT_OPTION."','".$ANSWER_DESCRIPTION."')";
mysql_query($query);
}
}
}
}
}
Please, help me getting a better solution.
Found following error after uploading the csv:
file 502 Bad Gateway
Once your file is uploaded then u should to fetch a row from uploaded using fgetcsv function of php
My Working Solution:
$p_Filepath ="your file path"
$file = fopen($p_Filepath, 'r');
$data = array();
$i=0;
while (! feof($file)) {
$data[$i] = (fgetcsv($file));
$i++;
}
$data1 = array();
for($j=1;$j<count($data);$j++){
$data1[$j] = array (
"date" => $data[$j][0],
"time" => $data[$j][1],
"type" => $data[$j][2],
"source" => $data[$j][3],
"contactName" => $data[$j][4],
"phone" => $data[$j][5],
"email" => $data[$j][6],
"address" => $data[$j][7],
"city" => $data[$j][8],
"state" => $data[$j][9],
"zip" => $data[$j][10],
"language" => $data[$j][11],
"practiceArea" => $data[$j][12],
"practiceCategory"=> $data[$j][13],
"actionable" => $data[$j][14],
"billable" => $data[$j][15],
"destNum" => $data[$j][16],
"callDuration" => $data[$j][17],
"pageUrl" => $data[$j][18],
"emailRec" => $data[$j][19]
);
$this->db->insert("contactReport",$data1[$j]);
}

Uploading logo using Codeigniter not working on editform

I have an editform for editing my company information. I also have a field for uploading a logo. When I click on choose file, and click Submit (the form) It stores the filename in my database as imagename.jpg for example.
I also want to add the image to the folder assets/uploads/. I tried it using the codeigniter upload class, same as I did on my other upload form, but this one does not work. I just don't know why.
Here's my editform:
<?= form_open_multipart('members/update/'.$id);?>
//other fields for editing company
<tr>
<td><?= form_label('Logo:'); ?></td>
<td><input type="file" name="logo" size="20" /></td>
</tr>
<tr>
<td><?= form_submit('submit', 'Opslaan');?> <?= form_reset('reset', 'Reset');?></td>
</tr>
</table>
<?= form_close()?>
My controller:
function update() //de update functie voor bovenstaande functie.
{
$id = $this->uri->segment(3);
$data = array(
'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
'Postcode' => $this->input->post('Postcode'),
'Plaats' => $this->input->post('Plaats'),
'Telefoonnummer' => $this->input->post('Telefoonnummer'),
'Email' => $this->input->post('Email'),
'Website' => $this->input->post('Website'),
'Profiel' => $this->input->post('Profiel'),
'Adres' => $this->input->post('Adres'),
);
if($this->input->post('logo')) { $data['logo'] = $this->input->post('logo'); }
$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;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
}
$this->members_model->updatebedrijf($id, $data);
$b = $this->session->userdata('idbedrijven');
redirect("members/$b");
}
function updatebedrijf($id, $data)
{
foreach($this->input->post('categorieen') as $cat){
$this->db->where('idbedrijven', $id);
$this->db->update('bedrijven', $data);
$to_bedrijfcategorieen2['idcategorieen'] = $this->input->post('categorieen');
$this->insert_bedrijfcat1($to_bedrijfcategorieen2);
};
}
My model:
function updatebedrijf($id, $data)
{
foreach($this->input->post('categorieen') as $cat){
$this->db->where('idbedrijven', $id);
$this->db->update('bedrijven', $data);
$to_bedrijfcategorieen2['idcategorieen'] = $this->input->post('categorieen');
$this->insert_bedrijfcat1($to_bedrijfcategorieen2);
};
}
It just does not upload. The path is the same as my other uploadfunction. that one works fine.
You have not set field name in the do_upload function
if ( ! $this->upload->do_upload("logo"))
{
$error = array('error' => $this->upload->display_errors());
}else{
$image_data = $this->upload->data();
}
And there is one thing wrong you have a if check for logo field and you are trying to get in post why ?? it should be
if($_FILES['logo']['name'] != '') { $data['logo'] = $_FILES['logo']['name']; }
if ( ! $this->upload->do_upload(?))
You should set file name as argument to upload function, since it is not default 'userfile'?
Not any of the solutions woked. This the way that I came up with.
if ($_FILES['userfile']['name'] != null) {
// upload configuration
$upload_config = array(
'upload_path' => './assets/uploads/',
'allowed_types' => 'jpeg|jpg|png',
'max_size' => 1048576,
'max_width' => 10240,
'max_height' => 7680,
'encrypt_name' => TRUE
);
// load upload library config
$this->load->library('upload', $upload_config);
if (!$this->upload->do_upload()) {
// assign upload errors
$data['upload_errors'] = $this->upload->display_errors();
// load page title
$page['title'] = "Edit Parent";
// fetch parent information
$this->db->select('Database Query');
// info data in row
$data['info'] = $this->db->get()->row();
// load view with page title
$this->load->view('temp/header', $page);
$this->load->view('editParents', $data);
$this->load->view('temp/footer');
} else {
$upload_photo = $this->upload->data();
// profile image
$parent_photo = $upload_photo['file_name'];
}
} else {
// profile image
$parent_photo = $this->input->post('profile_image');
}

Categories