Codeigniter multiple files uploads per field with input array key - php

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:

Related

Upload File in Edit Multiple Data Form

I'm trying to create an edit multiple data form like this using Laravel 8. In the form, you could upload only one file for each row. I could update the data without uploading file, but when I tried to update the file, it redirect me back to the form and no file uploaded. I already add enctype to my form. This is my code:
View:
<div class="custom-file" style="margin-left:10px; margin-right:10px;">
<input type="file" name="bukti[]" class="custom-file-input">
<label class="custom-file-label"></label>
</div>
Controller:
if($request->file('bukti') !=null) {
//upload file
$bukti=array();
if($files=$request->file('bukti')) {
foreach($files as $file) {
$name=$file->getClientOriginalName();
$path=$file->storeAs('blabla',$name);
$bukti[]=$name;
}
}
//Update multiple data
if(count($request->id) > 0) {
foreach($request->id as $item => $v) {
$data = array(
'id_laporan' => $laporan_indikators->id,
'id_pertanyaan' => $request->id_pertanyaan[$item],
'jumlah' => $request->jumlah[$item],
'keterangan' => $request->keterangan[$item],
'bukti' => $bukti[$item],
);
$data_laporans = DataLaporan::where('id',$request->id[$item])->first();
$data_laporans->update($data);
}
}
I already tried to fix it but I still didn't get a solution. Please help me because I'm still a beginner. I'm sorry for my bad English. Thank you.
UPDATE: I already tried to update the code to something like this:
Controller:
//upload file
if($files=$request->file('bukti')) {
foreach($files as $file) {
$name=$file->hashName();
$path=$file->storeAs('blabla',$name);
$bukti=$name;
}
}
//Update multiple data
if(count($request->id) > 0) {
foreach($request->id as $item => $v) {
$data = array(
'id_laporan' => $laporan_indikators->id,
'id_pertanyaan' => $request->id_pertanyaan[$item],
'jumlah' => $request->jumlah[$item],
'keterangan' => $request->keterangan[$item],
'bukti' => $bukti,
);
$data_laporans = DataLaporan::where('id',$request->id[$item])->first();
$data_laporans->update($data);
}
}
It uploaded the file and redirect me back to the index page after updating successfully, but when I check the database, the controller updated all of the bukti column value to the same file name. If I tried to update file for two rows, all of the bukti column is just update the value to the last uploaded file name. What I want is there's just one data for jumlah, keterangan, and one bukti file in a row, so I can have different files for each row. I don't really know how to fix this because I'm still a beginner. Thank you for your help.
Try to add the double question (??) mark for check whether the index of array is available or not:
<?php
if($request->file('bukti') !=null) {
//upload file
$bukti=array();
if($files=$request->file('bukti')) {
foreach($files as $file) {
$name=$file->getClientOriginalName();
$path=$file->storeAs('blabla',$name);
$bukti[]=$name;
}
}
//Update multiple data
if(count($request->id) > 0) {
foreach($request->id as $item => $v) {
$data = array(
'id_laporan' => $laporan_indikators->id,
'id_pertanyaan' => $request->id_pertanyaan[$item],
'jumlah' => $request->jumlah[$item],
'keterangan' => $request->keterangan[$item],
'bukti' => $bukti[$item] ?? '',
);
$data_laporans = DataLaporan::where('id',$request->id[$item])->first();
$data_laporans->update($data);
}
}
After trying for some times, finally I found a solution. Actually, I just need to give a condition if a file is uploaded in certain row.
View:
<div class="custom-file" style="margin-left:10px; margin-right:10px;">
<input type="file" name="bukti_{{ $data->id }}" class="custom-file-input">
<label class="custom-file-label"></label>
</div>
Controller:
if (count($request->id) > 0) {
$bukti = '';
foreach ($request->id as $item => $v) {
$id_item = $request->id[$item];
$file = $request->file('bukti_'.$id_item);
$data = array(
'id_laporan' => $laporan_indikators->id,
'id_pertanyaan' => $request->id_pertanyaan[$item],
'jumlah' => $request->jumlah[$item],
'keterangan' => $request->keterangan[$item],
);
//If file is updated
if ($file) {
$name = $file->hashName();
$path = $file->storeAs('blabla', $name);
$bukti = $name;
$data['bukti'] = $name;
}
$data_laporans = DataLaporan::where('id', $request->id[$item])->first();
$data_laporans->update($data);
}
}

Uploading multiple images and text input with php

I am working on a form which allows users upload text, location and 4 multiple images for a project, I have successfully written a code that uploads form data into my database but the problem I do face is that whenever I upload more than 1 image with this form, the form text and location input are been inserted into my database more than 1 times (to match the number of images I have uploaded). For example I Uploaded 3 images using the form and text "Hello World" and location "NY", output should be;
Hello World
NY
[image 1] [image 2] [image 3]
But instead output is
Hello World NY
Hello World NY
Hello World NY
[image 1] [image 2] [image 3]
I will like to stop the duplicate of the form text to match the number of images uploaded using the form for I have tried removing my query from the foreach statement but get no result after upload. Below is my code
<?php
// start session
session_start();
// db
include db.php";
// random_char
include "random_char.php";
// compress image
include "compress_image.php";
// from user id
$id = $_SESSION["id"];
$user = $_SESSION["name"];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// post validations
if (empty(trim($_POST['photo_post_box']))) {
// $post_box = null; // post box
$post_box_error = true; // post box is empty
} elseif (strlen($_POST['photo_post_box']) > 500) {
$post_box_error = true; // characters is greater than 500
} else {
$post_box = $_POST['photo_post_box'];
$post_box_error = false;
}
// location validation
if (empty(trim($_POST['photo_location']))) {
$location = ""; // location
$location_error = false; // location is empty
} elseif (strlen(preg_replace('/[^a-zA-Z]/m', '', $_POST["photo_location"])) < 2) {
$location_error = true; // location is less than 2
} elseif (strlen(preg_replace('/[^a-zA-Z]/m', '', $_POST["photo_location"])) > 20) {
$location_error = true; // location is greater than 20
} elseif (!preg_match("/^[A-Za-z-,\s]+$/ ", $_POST["photo_location"])) {
$location_error = true; // location has unwanted characters
} else {
$location = trim($_POST['photo_location']); // location
$location_error = false;
}
// image validations
$accepted_extensions = array(
"gif",
"png",
"jpg",
"jpeg"
); // extensions
$img = $_FILES["img"]; // images
foreach($img['name'] as $key => $name) {
$files = $_FILES['img'];
$img_extension = pathinfo($files["name"][$key], PATHINFO_EXTENSION); // image extention
$img_extension = strtolower($img_extension); // image extension
if (!file_exists($files['tmp_name'][$key])) {
$img_error = true;
} elseif (!in_array($img_extension, $accepted_extensions)) {
echo "<font color='red'>Invalid format</font>";
$img_error = true;
} elseif ($files["size"][$key] > 10485760) {
$img_error = true; // image is larger than 10mb
} else {
$img_error = false;
}
if ($post_box_error == false && $location_error == false && $img_error == false) {
$time = md5(microtime()); // micro time hashed with md5
$name_file = $project_name.".com(#".$user.")_".$time.$id; // rename image
$ext = substr($name, strrpos($name, '.') + 1); // extension
$uploaded_img = $name_file.'.'.$ext; // uploaded image
$save_to_dir = __DIR__."/../../img/".$uploaded_img; // save image to directory
$post_id = random_alphanumeric_string(8).'b'.$id; // post id
// `users_post`
$insert = "INSERT INTO users_post(post_id, by_user_id, post, post_location, date_n_time) VALUES(?, ?, ?, ?, NOW())";
$stmt = mysqli_prepare($db, $insert);
mysqli_stmt_bind_param($stmt, "siss", $post_id, $id, $post_box, $location);
mysqli_stmt_execute($stmt);
// `users_post_images`
$insert = "INSERT INTO users_post_images(post_id, image) VALUES(?, ?)";
$stmt = mysqli_prepare($db, $insert);
mysqli_stmt_bind_param($stmt, "ss", $post_id, $uploaded_img);
mysqli_stmt_execute($stmt);
// compress and save uploaded image in directory
compressImage($files['tmp_name'][$key], $save_to_dir, 60);
}
// close statement
mysqli_stmt_close($stmt);
}
}
// close db connection
mysqli_close($db);
?>
<form id="photo_post_box" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" name="post_box" enctype="multipart/form-data" accept-charset="utf-8">
<textarea class="form-control" name="photo_post_box" placeholder="Write something..."></textarea>
<div class="mt-1">
<input class="form-control" type="text" name="photo_location" placeholder="City, State">
</div>
<div class="mt-1">
<input type="file" name="img[]" id="img1" accept=".gif, .jpg, .png" required="required">
<input type="file" name="img[]" id="img2" accept=".gif, .jpg, .png">
<input type="file" name="img[]" id="img3" accept=".gif, .jpg, .png">
<input type="file" name="img[]" id="img4" accept=".gif, .jpg, .png">
</div>
<div class="mt-1">
<button name="upload">
<b>Upload</b>
</button>
</div>
</form>
Without going into code in great detail, here is generally what you are doing wrong and how you should do it.
The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows.
Array
(
[img] => Array
(
[name] => Array
(
[0] => bears.jpeg
[1] => big cat.jpeg
[2] => butterfly2.jpeg
[3] => chipmunk.jpeg
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
[2] => image/jpeg
[3] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpNKGKa2
[1] => /tmp/phpOCopiT
[2] => /tmp/phphEGfqK
[3] => /tmp/phpguKfyB
)
[error] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
[size] => Array
(
[0] => 162804
[1] => 133032
[2] => 118203
[3] => 164941
)
)
)
When you upload files, on the PHP side you will get a structure something like this:
So you have to walk through this structure to get all the files. The form data on the other hand is only stored once in $_POST.
So you must insert the form data once and the files you must use a loop to go through them all.
// INSERT form data first outside the loop
// Then go through the files in a loop
foreach ($_FILES["img"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
// INSERT file here
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = basename($_FILES["pictures"]["name"][$key]);
// Usually you have to do this
move_uploaded_file($tmp_name, "some/real/dir");
}
}

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.

insert multiple image data into database with codeigniter

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();
}

Uploading different unique files to the server and their names saved to the database

Before you start screen duplicate post, please understand that I searched here and the google but could find something that helps my situation.
Even as I am typing, something close to what I need was written in asp.net.
Here is the scenario.
I have 5 different unique files, each of which is a fieldname on the datatabase.
Here is a sample markup:
<form id="form1" name="contacts_form" method="post" action="save.php" enctype="multipart/form-data">
..
..
<td class="td_input_form"><input type="file" name="item1" size="50"></td>
<td class="td_input_form"><input type="file" name="item2" size="50"></td>
<td class="td_input_form"><input type="file" name="item3" size="50"></td>
<td class="td_input_form"><input type="file" name="item4" size="50"></td>
<td class="td_input_form"><input type="file" name="item5" size="50"></td>
..
..
</form>
We would like to upload all 5 files to a folder called uploads and then save their filename as well as additional form fields to the database.
I am having issues getting this to work.
<?php
// Connect to SQL Server database
include("../Connections/Connect.php")
//This is the directory where images will be saved
$target = "uploads";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if ($file_type!="application/pdf" || $file_type!="image/gif" || $file_type!="image/jpeg") {
$errors[] 'You can only upload PDFs, JPEGs or GIF files.<br>';
}
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$name='". ms_escape_string($_POST['nameMember']) ."';
$bandMember='". ms_escape_string($_POST['bandMember']) ."';
$pic1='". ms_escape_string(($_FILES['photo1']['name'])) ."';
$pic2='". ms_escape_string(($_FILES['photo2']['name'])) ."';
$pic3='". ms_escape_string(($_FILES['photo3']['name'])) ."';
$pic4='". ms_escape_string(($_FILES['photo4']['name'])) ."';
$pic5='". ms_escape_string(($_FILES['photo5']['name'])) ."';
$about='". ms_escape_string($_POST['aboutMember'];
$bands='". ms_escape_string($_POST['otherBands']) ."';
//Writes the information to the database
$sql="INSERT INTO tableName (nameMember,bandMember,photo1,photo2,photo3,photo4,photo5,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic1', '$pic2', '$pic3', '$pic4', '$pic5', '$about', '$bands')" ;
$objQuery = sqlsrv_query($conn, $sql);
//Writes the files to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//If all is ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded to the directory and records saved to the database";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
sqlsrv_close($conn);
}
?>
Somehow, I have the feeling I am confusing the upload file code with the variables to be inserted into the database.
Thank you in advance for your help.
INSERT INTO bids (BidDate,DueDate,DueTime,BidTitle,BidID,Description,BidIDFile,photo1,SignInSheet,TabSheet,Department,Xcontract,ContactEmail,ContactPhone,NumofBids,AwardDate,AwardRecip1,BidType,LastUpdate,Notes,BidStatus) VALUES ('03/27/2015', '03/27/2015','2:00pm','Test','TTTTTTI9','Testing','524767-3252.htm', '240','Jim Brown','jim.brown#yahoo.com','987-254-3311','3','03/25/2015','Johhny, Carey, Jenny','Property Sales','03/24/2015','Testing notes','1')
I thought you might want to see the actual INSERT statement and the declarations.
$sqlArr['values'][$i] = "'".ms_escape_string($_FILES['item']['name'][$i])."'";
$sqlArr['columns'][] = "BidIDFile";
$sqlArr['columns'][$i+=1] = "photo".$i;
$sqlArr['columns'][] = "SignInSheet";
$sqlArr['columns'][] = "TabSheet";
if(isset($sqlArr['columns'])) {
// Because this is dependent on all images being uploaded properly, you
// need more validation in your code. This code inserts no matter what.
$sql="INSERT INTO bids (BidDate,DueDate,DueTime,BidTitle,BidID,Description,".implode(",",$sqlArr['columns']).",Department,Xcontract,ContactEmail,ContactPhone,NumofBids,AwardDate,AwardRecip1,BidType,LastUpdate,Notes,BidStatus)
VALUES ('$bidDate', '$dueDate','$dueTime','$bidTitle','$bidId','$desc',".implode(",",$sqlArr['values']).", '$dept','$bidContact','$contactEmail','$contactPhone','$numBids','$awardDate','$awardrecip1','$bidType','$lastUpdate','$notes','$status'
)" ;
A couple of more pointers.
1, the fieldnames were coming in with single quotes. So, you may notice the implode columns doesn't have the single quotes anymore.
2, Also, we wanted the index position to start at 1 instead of 0 since photo fieldname begins as photo1, ...
Array
(
[txtBidDate] => 03/27/2015
[txtDueDate] => 03/27/2015
[txtDueTime] => 2:00pm
[BidTitle] => Test
[BidID] => TTTTTTI9
[Description] => Testing
[Department] => 240
[BidContact] => Jim Brown
[ContactEmail] => jim.brown#yahoo.com
[ContactPhone] => 987-254-3311
[NumofBids] => 3
[txtAwardDate] => 03/25/2015
[AwardRecip] => Johhny, Carey, Jenny
[BidType] => Property Sales
[txtLastUpdate] => 03/24/2015
[Notes] => Testing notes
[Status] => 1
)
Array
(
[item] => Array
(
[name] => Array
(
[0] => 524767-3252.htm
)
[type] => Array
(
[0] => text/html
)
[tmp_name] => Array
(
[0] => C:\Windows\Temp\phpAB56.tmp
)
[error] => Array
(
[0] => 0
[1] => 4
[2] => 4
[3] => 4
[4] => 4
[5] => 4
[6] => 4
[7] => 4
[8] => 4
)
[size] => Array
(
[0] => 60343
)
)
)
BidDate
DueDate
DueTime
Project Title
ID
Description
BidIDFILE - file upload
photo1 - file upload
photo2 - file upload
photo3 - file upload
photo4 - file upload
photo5 - file upload
photo6 - file upload
Department
SignInSheet - file upload
BidContact
ContactEmail
ContactPhone
NumBidReceived
TabulationSheet - file upload
AwardDate
AwardRecipient
BidType
LastUpdate
Notes
Status
///Code snip to upload files and insert records to the database:
$cols = (isset($cols) && is_array($cols))? implode(",",$cols):"";
$vals = (isset($vals) && is_array($vals))? implode(",",$vals):"";
//echo '<pre>';
//print_r($sql);
//print_r($cols);
//print_r($vals);
//echo '</pre>';
//echo '<br />';
//echo "insert into bids ($cols) values ($vals)";
sqlsrv_query($conn, $sql);
echo "Register Completed!<br>";
header('Location: admin.php');
You have a ton of things messed up, but this should be a working script. Aside from my above comments, I have notated below for additional information and concern:
FORM
<form id="form1" name="contacts_form" method="post" action="" enctype="multipart/form-data">
<table>
<tr>
<!-- You need to array these. The method you have is too manual
You could even use for() to create these -->
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
<td class="td_input_form"><input type="file" name="item[]" size="50"></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
PHP
<?php
// I can't check this for you...
include("../Connections/Connect.php");
// In general, you have no check to see that anything was submitted.
// That is something you may want to implement or else this script
// will autoload on page load regardless of $_FILES or $_POST submission
// You may want to add document root
$target = $_SERVER['DOCUMENT_ROOT']."/uploads";
// I am filtering the files incase there are empty uploads
// You need to have the proper file input name (item)
$_FILES['item']['name'] = array_filter($_FILES['item']['name']);
$_FILES['item']['type'] = array_filter($_FILES['item']['type']);
$_FILES['item']['size'] = array_filter($_FILES['item']['size']);
$_FILES['item']['tmp_name'] = array_filter($_FILES['item']['tmp_name']);
foreach($_FILES['item']['name'] as $i => $value ) {
$file_name = $_FILES['item']['name'][$i];
$file_size = $_FILES['item']['size'][$i];
$file_tmp = $_FILES['item']['tmp_name'][$i];
$file_type = $_FILES['item']['type'][$i];
$name = ms_escape_string($_POST['nameMember']);
$bandMember = ms_escape_string($_POST['bandMember']);
$about = ms_escape_string($_POST['aboutMember']);
$bands = ms_escape_string($_POST['otherBands']);
$sqlArr['values'][$i] = "'".ms_escape_string($_FILES['item']['name'][$i])."'";
$sqlArr['columns'][$i] = "photo".$i;
// At this point you are only notifying user.
// You have no code to prevent this limitation.
if ($file_type!="application/pdf" || $file_type!="image/gif" || $file_type!="image/jpeg")
$errors[] = 'You can only upload PDFs, JPEGs or GIF files.<br>';
// So far, this is just for notification, you haven't
// actually done anything about this limitation
if($file_size > 2097152)
$errors[]='File size must be less than 2 MB';
// Makes the folder if not already made.
if(!is_dir($target))
mkdir($target,0755,true);
//Writes the files to the server
if(move_uploaded_file($_FILES['item']['tmp_name'][$i], $target."/".$file_name)) {
//If all is ok
echo "The file ". $file_name. " has been uploaded to the directory and records saved to the database";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
if(isset($sqlArr['columns'])) {
// Because this is dependent on all images being uploaded properly, you
// need more validation in your code. This code inserts no matter what.
$sql="INSERT INTO tableName (nameMember,bandMember,`".implode("`,`",$sqlArr['columns'])."`,aboutMember,otherBands)
VALUES ('$name', '$bandMember',".implode(",",$sqlArr['values']).", '$about', '$bands')" ;
$objQuery = sqlsrv_query($conn, $sql);
sqlsrv_close($conn);
} ?>
EDIT: For further clarification on how to process the post and files try using processing functions that will return an array for use in an sql statement:
FORM:
Add this line in the form:
<td class="td_input_form"><input type="file" name="BidIDFile[]"></td>
PROCESSING:
function ProcessRequest($request = array())
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Create insert values
$insert['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$insert['cols'][] = "`".str_replace("txt","",$key)."`";
// For good measure, create an update string
$insert['update'][] = "`".str_replace("txt","",$key)."`".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$insert['bind']['cols'][] = "`".$key."`";
$insert['bind']['cols_bind'][] = ":".$key;
$insert['bind']['vals'][":".$key] = $value;
$insert['bind']['update'][] = "`".$key.'` = :'.$key;
}
// If there are cols/values return them
if(isset($insert))
return $insert;
}
}
function ProcessFiles($name = 'item',$target = '/uploads')
{
$target = $_SERVER['DOCUMENT_ROOT'].$target;
// Makes the folder if not already made.
if(!is_dir($target))
mkdir($target,0755,true);
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// You need to differentiate your type array names
$use_name = ($name == 'item')? 'photo':$name;
// To start at photo1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $target."/".$file_name)) {
// Format the key values for photo
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = ProcessRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
return $sql;
}
// Process files and post (or array in general)
$sql['post'] = ProcessRequest($_POST);
$sql['file'] = ProcessFiles('item');
$sql['BidIDFile'] = ProcessFiles('BidIDFile');
if(isset($sql['post']['cols']))
$cols[] = implode(",",$sql['post']['cols']);
if(isset($sql['file']['cols']))
$cols[] = implode(",",$sql['file']['cols']);
if(isset($sql['BidIDFile']['cols']))
$cols[] = implode(",",$sql['BidIDFile']['cols']);
if(isset($sql['post']['vals']))
$vals[] = implode(",",$sql['post']['vals']);
if(isset($sql['file']['vals']))
$vals[] = implode(",",$sql['file']['vals']);
if(isset($sql['BidIDFile']['vals']))
$vals[] = implode(",",$sql['BidIDFile']['vals']);
$cols = (isset($cols) && is_array($cols))? implode(",",$cols):"";
$vals = (isset($vals) && is_array($vals))? implode(",",$vals):"";
echo '<pre>';
print_r($sql);
print_r($cols);
print_r($vals);
echo '</pre>';
echo '<br />';
echo "insert into table ($cols) values ($vals)";
Will give you something like (I only put two post key/value pairs, that's why there is only two. In your case there would be a series of pairs):
Array
(
[post] => Array
(
[vals] => Array
(
[0] => 'asdfsda'
[1] => 'sdfsdfsdf'
)
[cols] => Array
(
[0] => `BidType`
[1] => `BidDate`
)
[update] => Array
(
[0] => `BidType` = 'asdfsda'
[1] => `BidDate` = 'sdfsdfsdf'
)
)
[file] => Array
(
[vals] => Array
(
[0] => '2015012203932.jpg'
[1] => 'a1400by1050.jpg'
)
[cols] => Array
(
[0] => `photo1`
[1] => `photo2`
)
[update] => Array
(
[0] => `photo1` = '2015012203932.jpg'
[1] => `photo2` = 'a1400by1050.jpg'
)
)
[BidIDFile] => Array
(
[vals] => Array
(
[0] => '87682315.jpg'
)
[cols] => Array
(
[0] => `BidIDFile`
)
[update] => Array
(
[0] => `BidIDFile` = '87682315.jpg'
)
)
)
insert into table (`BidType`,`BidDate`,`photo1`,`photo2`,`BidIDFile`) values ('','','2015012203932.jpg','a1400by1050.jpg','87682315.jpg')

Categories