insert multiple image data into database with codeigniter - php

i have a problem for looping data and save to database. the result of this insert data contains only one. and what is the differences in insert() with insert_batch() ? i'm sorry CTRL + K on my keyboard is not function.
my view :
<?php echo form_open('proses_tambah_produk')?>
<input type="file" id="gambar2" name="gambar_tambah[]" class="form-control" style="width:90%;display:initial;margin-right:10px;margin-bottom:5px;">
<label style="background-color:red;color:white;border-radius:50%;padding:3px;" id="idGambar2" class="hapus_gambar glyphicon glyphicon-remove"></label>
<input type="file" id="gambar2" name="gambar_tambah[]" class="form-control" style="width:90%;display:initial;margin-right:10px;margin-bottom:5px;">
<label style="background-color:red;color:white;border-radius:50%;padding:3px;" id="idGambar2" class="hapus_gambar glyphicon glyphicon-remove"></label>
<?php echo form_close()?>
my controller :
function proses_tambah_produk(){
$config['upload_path'] = 'assets/img/produk';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 1000;
$config['overwrite'] = TRUE;
//$config['max_width'] = 1024;
//$config['max_height'] = 768;
$this->load->library('upload', $config);
$files = $_FILES;
$count = count($_FILES['gambar_tambah']['name']);
for($i=0; $i<$count; $i++)
{
$_FILES['gambar_tambah']['name']= $files['gambar_tambah']['name'][$i];
$_FILES['gambar_tambah']['type']= $files['gambar_tambah']['type'][$i];
$_FILES['gambar_tambah']['tmp_name']= $files['gambar_tambah']['tmp_name'][$i];
$_FILES['gambar_tambah']['error']= $files['gambar_tambah']['error'][$i];
$_FILES['gambar_tambah']['size']= $files['gambar_tambah']['size'][$i];
$this->upload->do_upload('gambar_tambah');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
$tambahan = $_FILES['gambar_tambah']['name'];
$this->produk_adm->add($data, $gambar, $tambahan);
}
my model :
function add($tambahan){
$last_insert_id = $this->db->insert_id();
$data_gambar = array(
'id_produk' => $last_insert_id,
'gambar' => $tambahan,
);
$this->db->insert('produk_image', $data_gambar);
return $this->db->insert_id();
}

$filesCount = count($_FILES['photo_gallery']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['gambar_tambah']['name'] = $_FILES['photo_gallery']['name'][$i];
$_FILES['gambar_tambah']['type'] = $_FILES['photo_gallery']['type'][$i];
$_FILES['gambar_tambah']['tmp_name'] = $_FILES['photo_gallery']['tmp_name'][$i];
$_FILES['gambar_tambah']['error'] = $_FILES['photo_gallery']['error'][$i];
$_FILES['gambar_tambah']['size'] = $_FILES['photo_gallery']['size'][$i];
$file_name=$this->crud->upload_file('gambar_tambah',$upload_image_path);
$image_data[$i]['image'] = $file_name;
$this->crud->add('table_name',$image_data[$i]);
}

you can't use same id name twice. The id value must be unique for every field. Your code for upload is wrong you are assigning value of
$_FILES['gambar_tambah']['name']= $files['gambar_tambah']['name'][$i];
You can't do this insted you just assign value to a variable like
$image_name = $_FILES['gambar_tambah']['name'];
and insert that into database every time when loop runs or make array of it and insert it into one filed by implode function.

when you are calling model you have used three parameters and in model you are using one.
use
$this->load->model('produk/adm');
$this->produk_adm->add($tambahan);
instead of
$this->produk_adm->add($data, $gambar, $tambahan);
and in model
function add($tambahan){
$last_insert_id = $this->db->insert_id();
$data_gambar = array(
'id_produk' => $last_insert_id, // if it is auto increment in db, remove this line
'gambar' => $tambahan,
);
$this->db->insert('produk_image', $data_gambar);
return $this->db->insert_id();
}

Related

Codeigniter multiple files uploads per field with input array key

I have here multiple fields with multiple files uploads with array key name. I need to uploads multiple files per field and pass the filenames in array with keys into the model.
I really need this, hoping for someone would help me.
Thanks.
Here's the example of my fields
//with 2 or more files
<input accept="application/pdf" name="vtc_file[0]" id="vtc_file0" type="file" multiple/>
//with 2 or more files
<input accept="application/pdf" name="vtc_file[1]" id="vtc_file1" type="file" multiple/>
<?php
$count = count($_FILES['vtc_file']['name']);
for ($i=0; $i < $count; $i++)
{
foreach ($_FILES['vtc_file'] as $key1 => $value1)
{
foreach ($value1 as $key2 => $value2)
{
$files[$key2][$key1] = $value2;
}
}
}
$_FILES = $files;
$document_config['upload_path'] = 'uploads/';
$document_config['allowed_types'] = 'pdf';
$this->load->library('upload', $document_config);
foreach ($_FILES as $fieldname => $fileObject)
{
if (!empty($fileObject['name']))
{
$this->upload->initialize($document_config);
if (!$this->upload->do_upload($fieldname))
{
$errors = $this->upload->display_errors();
}
else
{
$results = $this->models->save();
}
}
}
I've made a demo for you, I've explained the steps in the code itself. Hope it works for you.
View
<form action="<?Php echo base_url('home/myfunc'); ?>" method="POST" enctype="multipart/form-data">
<!-- You need to make an array of input fields(See {name}) -->
<input accept="application/pdf" name="vtc_file[0][]" id="vtc_file0" type="file" multiple/>
<!-- If the usdr uploads only one file it will be stored like vtc_file[0][1] = 'filename.pdf' and so on.-->
<br>
<input accept="application/pdf" name="vtc_file[1][]" id="vtc_file1" type="file" multiple/><br>
<button type="submit" value="submit">Submit</button>
</form>
Controller
function myfunc(){
// check if the $_FILES is not empty(your validation here) then perform these actions↓↓
foreach ($_FILES['vtc_file']['name'] as $key1 => $value1){ // We only need to loop through all the input fields(vtc_file)
foreach ($value1 as $key2 => $value2){ // loop through name of all the files uploaded
// Make a new dummy element(userfile) with the file(vtc_file') details in it
$_FILES['userfile']['name'] = $_FILES['vtc_file']['name'][$key1][$key2];
$_FILES['userfile']['type'] = $_FILES['vtc_file']['type'][$key1][$key2];
$_FILES['userfile']['tmp_name'] = $_FILES['vtc_file']['tmp_name'][$key1][$key2];
$_FILES['userfile']['error'] = $_FILES['vtc_file']['error'][$key1][$key2];
$_FILES['userfile']['size'] = $_FILES['vtc_file']['size'][$key1][$key2];
$config['upload_path'] = './uploads/aaa'; // path to the folder
$config['allowed_types'] = 'pdf';
$config['max_size'] = 1000;
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config); // load the {upload} library
$this->upload->initialize($config); // initialize the library
if (!$this->upload->do_upload("userfile")){ // upload the file(current)
$data['errors'][$key1][$key2] = $this->upload->display_errors(); // if any error store them in {errors} variable with keys
}else{
$upload_data = $this->upload->data(); // get the uploaded file data
$data['filename'][$key1][$key2] = $upload_data['file_name']; // store the upload file name in {filename} variable with keys
}
}
}
//load model {event_model}
$this->load->model('event_model');
$success = $this->event_model->save_file($data['filename']); // call model function
// check if query successful
if($success){
// do something (Load a view)
// You can show uploaded files in your view with $data['filename'][$key1][$key2]
// And the errors of files that couldn't be uploaded with $data['errors'][$key1][$key2]
echo '<pre>'; print_r($data['errors']);
}else{
// do something else
}
}
Model
function save_file($data){
echo '<pre>'; print_r($data);
// Your insert query here.
return true;
}
Output:
Model: $filename array
Array
(
[0] => Array
(
[0] => Account_Software______Payment.pdf
[1] => Account_Software______RTGS_Report.pdf
)
[1] => Array
(
[0] => BUSINESS_PROFILE.pdf
)
)
Controller: $errors array
Array
(
[1] => Array
(
[1] =>
The filetype you are attempting to upload is not allowed.
)
)
Images:

How to declare variable outside if and for statement that already declared in CodeIgniter

I'm trying to update my images table with new ones.
This is my controller:
if(!empty($_FILES['gambar']['name'])){
$filesNumber = sizeof($_FILES['gambar']['tmp_name']);
$files = $_FILES['gambar'];
$config['upload_path'] = './assets/img/pics/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['encrypt_name'] = true;
for ($i = 0; $i < $filesNumber ; $i++) {
$_FILES['gambar']['name'] = $files['name'][$i];
$_FILES['gambar']['type'] = $files['type'][$i];
$_FILES['gambar']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['gambar']['error'] = $files['error'][$i];
$_FILES['gambar']['size'] = $files['size'][$i];
$this->upload->initialize($config);
if($this->upload->do_upload('gambar')){
$data = $this->upload->data();
$insert[$i]['kode_asset'] = $this->input->post('kode');
$insert[$i]['gambar'] = $data['file_name'];
}
}
$this->db->insert_batch('gambar', $insert);
redirect('admin/asset','refresh');
}
This is input for multiple files:
<input type="file" name="gambar[]" id="gambar" class="form-control-file" multiple>
But it give Undefined variable: insert notice at the insert_batch syntax and You must use the "set" method to update an entry. db error every time. Can someone help me?
check the statement:
// check filesNumber value, after see this , you may fix this quickly.
$filesNumber = sizeof($_FILES['gambar']['tmp_name']);

Use inserted ids from Laravel and Dropzone image uploaded data

I have a form with a Dropzone div, for massive image uploads with another data.
But, as the images are uploaded with ajax I need to know which Id's are assigned to those images.
The problem became when I save those ids in the session data. It just saves the first and the latest ids.
For example, when I submit 4 images it returns me the second and the last id.
😒
My controller method (via Ajax):
public function store(Request $request)
{
$photos = $request->file('file');
if (!is_array($photos))
$photos = [$photos];
if (!is_dir($this->photos_path))
mkdir($this->photos_path, 0777);
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$name = sha1(date('YmdHis') . str_random(30));
$save_name = $name . '.' . $photo->getClientOriginalExtension();
$resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save($this->photos_path . '/' . $resize_name);
$photo->move($this->photos_path, $save_name);
$upload = new UploadedImages();
$upload->filename = $save_name;
$upload->resized_name = $resize_name;
$upload->original_name = basename($photo->getClientOriginalName());
$upload->user_id = Auth::id();
$upload->save();
Session::push('uploaded_images_ids', $upload->id);
}
return Response::json(['message' => 'Image saved Successfully'], 200);
}
Response with Debug bar (should response 4 ids, not 2):
You can create an array to store your image and id
Here is the idea below
$image_array = [];
for ($i = 0; $i < count($photos); $i++) {
....
array_push($image_array,['image_name' => $save_name, 'image_id' => $upload->id]);
}

I cant insert multiple photos together with multiple rows

I cant insert multiple photos together with multiple rows.
I have here input fields:
<input name="u_code[]" required="required" style="margin:0px; ">
<input name="u_name[]" required="required" style="margin:0px; ">
<input name="u_address[]" required="required" style="margin:0px; ">
<input name="photo[]" required="required" style="margin:0px; ">
and this is my controller:
function user_add()
{
if ($_POST)
{
$u_id =$this->input->post('u_id');
$u_code =$this->input->post('u_code');
$u_name =$this->input->post('u_name');
$u_address = $this->input->post('u_address');
$data = array();
for ($i = 0; $i < count($this->input->post('u_id')); $i++)
{
$data[$i] = array(
'u_id' => $u_id[$i],
'u_code' => $u_code[$i],
'u_name' => $u_name[$i],
'u_address' => $u_address[$i],
);
}
$insert = $this->user_model->user_add($data);
echo json_encode(array("status" => TRUE));
}
}
My problem is i dont know where what exact code should be add to upload photos in a multiple rows.
please check photo here:
screenshot of input field
Thanks advance for the help..
Try this,
function user_add()
{
if ($_POST) {
$u_id = $this->input->post('u_id');
$u_code = $this->input->post('u_code');
$u_name = $this->input->post('u_name');
$u_address = $this->input->post('u_address');
$data = array();
for ($i = 0; $i < count($this->input->post('u_id')); $i++) {
$data[$i] = array(
'u_id' => $u_id[$i],
'u_code' => $u_code[$i],
'u_name' => $u_name[$i],
'u_address' => $u_address[$i],
);
$insert = $this->user_model->user_add($data);
}
echo json_encode(array("status" => true));
}
}
Have a look at this code may this help in understanding you how to handle multiple images
$files = $_FILES;
$count = count($_FILES['uploadfile']['name']);
for($i=0; $i<$count; $i++)
{
$_FILES['uploadfile']['name']= $files['uploadfile']['name'][$i];
$_FILES['uploadfile']['type']= $files['uploadfile']['type'][$i];
$_FILES['uploadfile']['tmp_name']= $files['uploadfile']['tmp_name'][$i];
$_FILES['uploadfile']['error']= $files['uploadfile']['error'][$i];
$_FILES['uploadfile']['size']= $files['uploadfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());//function defination below
$this->upload->do_upload('uploadfile');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
$_FILE it is an associative array of items uploaded to the current script via the POST method.for the further look this helper link
it's an automatic variable available within all scopes of the script
function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = LARGEPATH; //give the path to upload the image in folder
$config['remove_spaces']=TRUE;
$config['encrypt_name'] = TRUE; // for encrypting the name
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '78000';
$config['overwrite'] = FALSE;
return $config;
}
Some basic tip:
An input element must have multiple=" multiple" or just multiple.Load upload Library.
$this->upload->do_upload() will upload the file selected in the given field name to the destination folder.
$this->upload->data() returns an array of data related to the uploaded file like the file name, path, size etc.

How to delete uploaded image using jQuery / Ajax / PHP?

I am using following script to upload images. Here is the link : http://filer.grandesign.md/
Using this script It's allowing the preview after upload the image. Like bellow image :
You can see that, it's also allowing to delete the Image - See red bucket icon
What I am doing now :
When I upload the image I renamed the uploaded image and save it to database.
The code is bellow :
require_once('class.upload.php');
if(!isset($_FILES['files'])) {
die();
}
$files = array();
foreach ($_FILES['files'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new upload($file);
if ($handle->uploaded) {
$handle->file_new_name_body = 'mpic_list_'.uniqid('', true);
$menu_list_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 360;
$handle->image_y = 240;
$handle->process('images/menu_images/');
$handle->file_new_name_body = 'mpic_small_'.uniqid('', true);
$menu_small_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 100;
$handle->image_y = 65;
$handle->process('images/menu_images/');
$handle->file_new_name_body = 'mpic_large_'.uniqid('', true);
$menu_large_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 700;
$handle->image_y = 470;
$handle->process('images/menu_images/');
if ($handle->processed) {
$all_images = $menu_list_image . $menu_small_image . $menu_large_image;
$u_id = (int) $_SESSION['logged_user_id'];
if(!isset($_SESSION['last_id'])) {
// insert upload image section data...
$insert_menu_details = mysqli_query($conn, "INSERT INTO products (p_id) VALUES ('')");
$last_id = mysqli_insert_id($conn);
$insert_upload_image = mysqli_query($conn, "INSERT INTO product_images VALUES ('', '$menu_large_image', '$menu_list_image', '$menu_small_image', '$last_id', '$u_id')");
$_SESSION['last_id'] = $last_id;
} else {
// update upload image section data
$session_last_id = $_SESSION['last_id'];
$update_upload_image = mysqli_query($conn, "INSERT INTO product_images VALUES ('', '$menu_large_image', '$menu_list_image', '$menu_small_image', '$session_last_id', '$u_id')");
}
$handle->clean();
} else {
//echo 'error : ' . $handle->error;
echo 'Error';
}
}
}
What I need :
Now I want to delete my uploaded image. But here is an issue which is : by default this script is deleting the uploaded image using following PHP line :
<?php
if(isset($_POST['file'])){
$file = 'images/menu_images/' . $_POST['file'];
if(file_exists($file)){
unlink($file);
}
}
?>
But I can't delete it because when I upload the image to folder (images/menu_images/) I renamed it to something like that : abedkd12415775554.jpg
My Question is How can I delete my uploaded image using this script ?
You need to return the new images name that you are generating from server scripting like-
In the loop you are executing for inserting filename in database-
$array = array("oldName" => "newName");
echo json_encode($array);
You can also use numeric index if you are using some logic at your javascript end for creating array.
In javascript on delete option you can retrieve the value by using the image name and can perform delete.
check this
$res=mysqli_query("SELECT file FROM tbl_uploads WHERE id=".$_GET['remove_id']);
$row=mysqli_fetch_array($res);
mysqli_query("DELETE FROM tbl_uploads WHERE id=".$_GET['remove_id']);
unlink("uploads/".$row['file']);
Replace Your table and id name

Categories