PHP/MySQL - Data entered twice when doing single upload - php

I am trying to upload image to database MySQL. But I have a problem, when I am trying to upload one image, the image inserted twice.
For example:
I have "A.jpg" if I try to upload it
the inserted data will be like "A.jpg,A.jpg"
What I want in database "A.jpg"
and if I try to upload multiple images like "A.jpg,B.jpg and C.jpg"
the inserted data will be like "B.jpg,B.jpg,C.jpg,C.jpg"
What I want in database "A.jpg,B.jpg,C.jpg"
I've tried to search on google but no results, anyone can help me to resolve this problem ? Thanks
Here is my code :
include('koneksi.php');
date_default_timezone_set('Asia/Jakarta');
$id_user = $_POST['id_user'];
$caption = $_POST['caption'];
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
$explode = explode('.', $name);
$ext = end($explode);
$updatdName = $explode[0] . time() .'.'. $ext;
$path = 'gallery/';
$path = $path . basename( $updatdName );
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','JPG','jpeg','JPEG','gif','GIF','bmp','BMP','png','PNG');
$max_file_size = 1024*1024*2;; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_file_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
// if there is no error then set values
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$errors = array();
if(!file_exists('gallery')) {
mkdir('gallery', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<script>window.history.back()</script>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
if(!empty($files)) {
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$names = implode(',', $files['file_name']);
$sizes = implode(',', $files['size']);
$types = implode(',', $files['type']);
$sql="INSERT into status VALUES(NULL, '$id_user', '$names','$caption','foto',NOW()); ";
mysqli_query($koneksi, $sql);
}

You're setting $files['file_name'][] in the while loop and also right before inserting into the DB. You just need to remove 2nd call to $files['file_name'][] = $updatdName;
Here is a simplified version of what you're doing.
<?php
$_FILES[] = ['name' => 'A'];
$_FILES[] = ['name' => 'B'];
$_FILES[] = ['name' => 'C'];
$files = [];
foreach ($_FILES as $file) {
$updatdName = $file['name'];
// You're setting it here
$files['file_name'][] = $updatdName;
}
if (!empty($files)) {
// And also here.
$files['file_name'][] = $updatdName;
$names = implode(',', $files['file_name']);
echo $names;
}

Related

how to update multiple images in laravel?

i want store the images for product the product having multiple images the problem is that i want to update the images problem is images are updated but the entry never goes to database. instead it stores same entry two times.
if($request->hasfile('image')) { //here i got images
$file = $request->file('image');
$file_count= count($file); //for updating multiple images
for ($i=0; $i < $file_count; $i++) {
$imagesize = $file[$i]->getClientSize();
$imageexten = $file[$i]->getClientOriginalExtension();
$product_image_count = count($request->productimagename);
for ($i=0; $i < $product_image_count; $i++) {
if($file_count != 1) {
$new_name = $request->productimagename[$i].$i.".".$imageexten;
} else {
$new_name = $request->productimagename[$i].".".$imageexten;
}
$product_image_path ='images/frontendimage/product_image/'.$new_name;
Image::make($file[$i])->save($product_image_path);
foreach ($product->images as $key => $value) {
product_image::find($value->id)->where('product_id','=',$product->id)
->update(['image_name'=> $new_name,'image_url'=>$product_image_path,
'modified_by'=>Auth::user()->id]);
}
}
}
}
if ($request->has('unit_images'))
{
$promotion = [];
foreach ($request->file('unit_images') as $key => $file) {
$filenameWithExt = $file->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$fileNameToStore = uniqid() . '.' . $extension;
$path = $file->storeAs("$directory/unit_images/$b/$unit_num", $fileNameToStore, 'public');
$this->validate($request, [
'images' => 'dimensions:min_width=250,min_height=250'
]);
$b_id = $request->building_name;
$unitimg = UnitImage::where('unit_id', '=', $unit_store_id)->get();
$new=strlen($unitimg);
if ($new!='2') {
foreach ($unitimg as $get2) {
$get2->delete();
}
$nn=New UnitImage();
$nn->images = $path;
$nn->unit_id = $unit_store_id;
$nn->save();
}
if ($new=='2') {
$nn = New UnitImage();
$nn->images = $path;
$nn->unit_id = $unit_store_id;
$nn->save();
}
}
}
Input Field -
<input type="file" name="images[]" class="form-control" multiple required />
Controller -
$imagesName = array();
$imagesPath = array();
if($files=$request->file('images')){
foreach (Input::file('images') as $file) {
$name = strtolower($file->getClientOriginalName());
$name = preg_replace('/\s+/', '_', $name);
$img = Image::make($file);
$path = 'your/path/'.$name;
$img->save($path);
$imagesName[] = $name;
$imagesPath[] = $path;
}
}
This will upload multiple images to your server and you will get uploaded image names from $imagesName[] and path from $imagesPath[].
Now you can use those according to your BD structure.

How to Upload excel data to mysql database using codeigniter?

I have codeigniter application, Now i need to Upload excel using the codigniter.
How to do that. I follow some Online tutorials, but there are not complete one. Specially there are no what is the library they use.
if(isset($_POST['Submit']))
{
$mimes = array('application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.oasis.opendocument.spreadsheet','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
if(in_array($_FILES["file"]["type"],$mimes))
{
$uploadFilePath = 'uploads/'.basename($_FILES['file']['name']);
$filename = pathinfo($uploadFilePath);
$f = array("name"=>$filename['filename']);
foreach ($f as $k)
{
$policy = $k;
}
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath);
$Reader = new SpreadsheetReader($uploadFilePath);
$totalSheet = count($Reader->sheets());
//echo "You have total ".$totalSheet." sheets".
/* For Loop for all sheets */
for($i=0;$i<$totalSheet;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$treeno ++;
$policyno = isset($Row[0]) ? $Row[0] : '';
$act_treeno = isset($Row[1]) ? $Row[1] : '';
$dbh = isset($Row[2]) ? $Row[2] : '';
$height = isset($Row[3]) ? $Row[3] : '';
$pno = substr($policyno, -6);
$treeno = $pno.'_'.$act_treeno.'_T';
$query = "insert into tbl_trees(policyno,actual_treeno,dbh,height,treeno) values('".$policyno."','".$act_treeno."','".$dbh."','".$height."','".$treeno."')";
echo '</br>';
$mysqli->query($query);
this is work, but i have not idea to use this method in codeigniter.
First think you need upload that file then try open and prepare data for insert-
$fileName = $_FILES['file']['name'];
$uploadData = array();
if (!empty($fileName)) {
$config['upload_path'] = './your location/';
$config['allowed_types'] = 'txt|csv|xls|xlsx';
$config['max_size'] = 2048;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('file')) {
json_error("File Upload Error", $this->upload->display_errors(), 400);
} else {
$uploadData = array('upload_data' => $this->upload->data());
}
}//if
prepare data for insert-
if (!empty($uploadData)) {
$fileName = $uploadData['upload_data']['file_name'];
$data = array(); //empty array;
$fileInfo = fopen(base_url() . 'your file location/' . $fileName, "r");
$i = 0;
while (!feof($fileInfo)) {
$colInfo = fgets($fileInfo); //fgets means read file in line by line.
//prefer data to save
$data[$i]['your_column'] = $colInfo;
$i++;
}//while
fclose($fileInfo);
}
insert batch data-
$this->db->insert_batch('dbtable', $data);

AWS S3 PhPdolphin integration

So my goal was it to implement Amazon S3 image uploads to the PhPDolphin script, unfortunately I've run into a few Issues, if I add the code in the script just doesn't load and since the script doesn't have an error log I'm clueless as to what went wrong, for licensing reasons I'm unable to publish the entire script here but I will post a snipped of the affected area.
/includes/classes.php [Default (Just a small snippet of the 4000 lines of code within this file)]
function validateMessage($message, $image, $type, $value, $privacy) {
// If message is longer than admitted
if(strlen($message) > $this->message_length) {
$error = array('message_too_long', $this->message_length);
}
// Define the switch variable
$x = 0;
if($image['name'][0]) {
// Set the variable value to 1 if at least one image name exists
$x = 1;
}
if($x == 1) {
// If the user selects more images than allowed
if(count($image['name']) > $this->max_images) {
$error = array('too_many_images', count($image['name']), $this->max_images);
} else {
// Define the array which holds the value names
$value = array();
$tmp_value = array();
foreach($image['error'] as $key => $err) {
$allowedExt = explode(',', $this->image_format);
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
if(!empty($image['size'][$key]) && $image['size'][$key] > $this->max_size) {
$error = array('file_too_big', fsize($this->max_size), $image['name'][$key]); // Error Code #004
break;
} elseif(!empty($ext) && !in_array(strtolower($ext), $allowedExt)) {
$error = array('format_not_exist', $this->image_format, $image['name'][$key]); // Error Code #005
break;
} else {
if(isset($image['name'][$key]) && $image['name'][$key] !== '' && $image['size'][$key] > 0) {
$rand = mt_rand();
$tmp_name = $image['tmp_name'][$key];
$name = pathinfo($image['name'][$key], PATHINFO_FILENAME);
$fullname = $image['name'][$key];
$size = $image['size'][$key];
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
// $finalName = str_replace(',', '', $rand.'.'.$this->db->real_escape_string($name).'.'.$this->db->real_escape_string($ext));
$finalName = mt_rand().'_'.mt_rand().'_'.mt_rand().'.'.$this->db->real_escape_string($ext);
// Define the type for picture
$type = 'picture';
// Store the values into arrays
$tmp_value[] = $tmp_name;
$value[] = $finalName;
// Fix the image orientation if possible
imageOrientation($tmp_name);
}
}
}
if(empty($error)) {
foreach($value as $key => $finalName) {
move_uploaded_file($tmp_value[$key], '../uploads/media/'.$finalName);
}
}
// Implode the values
$value = implode(',', $value);
}
And then my edited version that is supposed to upload the images automatically to Amazon S3.
/includes/classes.php [edited] (the s3 code is on the far bottom of the snippet)
function validateMessage($message, $image, $type, $value, $privacy) {
// If message is longer than admitted
if(strlen($message) > $this->message_length) {
$error = array('message_too_long', $this->message_length);
}
// Define the switch variable
$x = 0;
if($image['name'][0]) {
// Set the variable value to 1 if at least one image name exists
$x = 1;
}
if($x == 1) {
// If the user selects more images than allowed
if(count($image['name']) > $this->max_images) {
$error = array('too_many_images', count($image['name']), $this->max_images);
} else {
// Define the array which holds the value names
$value = array();
$tmp_value = array();
foreach($image['error'] as $key => $err) {
$allowedExt = explode(',', $this->image_format);
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
if(!empty($image['size'][$key]) && $image['size'][$key] > $this->max_size) {
$error = array('file_too_big', fsize($this->max_size), $image['name'][$key]); // Error Code #004
break;
} elseif(!empty($ext) && !in_array(strtolower($ext), $allowedExt)) {
$error = array('format_not_exist', $this->image_format, $image['name'][$key]); // Error Code #005
break;
} else {
if(isset($image['name'][$key]) && $image['name'][$key] !== '' && $image['size'][$key] > 0) {
$rand = mt_rand();
$tmp_name = $image['tmp_name'][$key];
$name = pathinfo($image['name'][$key], PATHINFO_FILENAME);
$fullname = $image['name'][$key];
$size = $image['size'][$key];
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
// $finalName = str_replace(',', '', $rand.'.'.$this->db->real_escape_string($name).'.'.$this->db->real_escape_string($ext));
$finalName = mt_rand().'_'.mt_rand().'_'.mt_rand().'.'.$this->db->real_escape_string($ext);
// Define the type for picture
$type = 'picture';
// Store the values into arrays
$tmp_value[] = $tmp_name;
$value[] = $finalName;
// Fix the image orientation if possible
imageOrientation($tmp_name);
}
}
}
if(empty($error)) {
foreach($value as $key => $finalName) {
if (!class_exists('S3'))require_once('S3.php');
//AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', 'myaccesskey');
if (!defined('awsSecretKey')) define('awsSecretKey', 'mysecretkey');
//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);
S3::outObject(
'$tmp_value[$key]',
'zepstrca',
'.$finalName);',
S3::ACL_PUBLIC_READ
array(),
array(),
S3::STORAGE_CLASS_STANDARD
);
}
// Implode the values
$value = implode(',', $value);
}
And yes I did add my own access and secret key :)
Any help would be greatly appreciated and will be credited!
Links to the products and API used in this:
[PhPDolphin] [S3.php API on Github]
This is how you can use the library i am using, i hope it will fix your problems (make sure the folder on the bucket actually exists otherwise just upload something to the root of the bucket)
require_once 'S3.php';
$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->putObjectFile('/folderOnServer/picture.jpg', awsBucket, '/folderOnBucket/newName.jpg');

class.upload.php and file extension missing

I'm using class.upload.php for images. Resizing works correctly with name and extension into the folder, but i have a problem storing the name into mysql database. There's no file extension (.jpg, .gif etc)... why? how can i resolve the problem?
Thanks
/* ========== SCRIPT UPLOAD MULTI IMAGES ========== */
include('class.upload.php');
$dir_dest="../../images/gallery/";
$files = array();
foreach ($_FILES['fleImage'] 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) {
$mainame = $handle->file_dst_name;
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_big = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_big;
$handle->image_resize = true;
$handle->image_x = 460;
$handle->image_ratio_y = true;
// $handle->image_y = 400;
$handle->Process($dir_dest);
//Thumbnail
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_small = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_small;
$handle->image_resize = true;
$handle->image_x = 180;
$handle->image_ratio_y = true;
// $handle->image_y = 120;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
header("Location: index.php"); //echo 'image resized';
$handle->clean();
$query_img="INSERT into tbl_images (file_name, pd_image, pd_thumbnail) VALUES('$nome','$result_big', '$result_small')";
$result2 = dbQuery($query_img);
} else {
echo 'error : ' . $handle->error;
}
}
}
// END SCRIPT UPLOAD MULTI IMAGES
header("Location: index.php");
}
You are removing the extension with this code
$result_big = str_replace("." . $extension,"",$image1);
I dont know why you do that. anyway you can add it back by adding following line after the $handle->file_new_name_body = $result_big;
$handle->file_new_name_ext = $extension;
You have replaced the extention with empty string here using str_replace
$result_small = str_replace("." . $extension,"",$image1);
and here
$result_big = str_replace("." . $extension,"",$image1);
update below lines just add .$extension at the end
$handle->file_new_name_body = $result_big.$extension;
and
$handle->file_new_name_body = $result_small.$extension;
just change query like this
$query_img="INSERT into tbl_images (
file_name,
pd_image,
pd_thumbnail
) VALUES (
'$nome',
'{$result_big}.{$extension}',
'{$result_small}.{$extension}')";
I will suggest you to have same filename for pd_image and pd_thumbnail, just prefix thumb with thumb_ that will make your life easier in front end.
this way you can access any image thumbnail just by prefixing it with thumb_ with pd_image and you don't have to store pd_thumbnail in database.

I can't upload multiple images using PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - Upload multiple images
I want to upload multiple images using PHP and I am stuck. I have the code but it uploads only 1 image.
<?php
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND (!empty($_POST['make'])) AND (!empty($_POST['model'])) AND (!empty($_POST['engine'])) AND (!empty($_POST['mileage'])) AND (!empty($_POST['exterior'])) AND (!empty($_POST['interior'])) AND (!empty($_POST['transmission'])) AND (!empty($_POST['body'])) AND (!empty($_POST['fuel'])) AND (!empty($_POST['drive'])) AND (!empty($_POST['doors'])) AND (!empty($_POST['description']))) {
$year = htmlspecialchars($_POST['year']);
$make = htmlspecialchars($_POST['make']);
$model = htmlspecialchars($_POST['model']);
$engine = htmlspecialchars($_POST['engine']);
$mileage = htmlspecialchars($_POST['mileage']);
$exterior = htmlspecialchars($_POST['exterior']);
$interior = htmlspecialchars($_POST['interior']);
$transmission = htmlspecialchars($_POST['transmission']);
$body = htmlspecialchars($_POST['body']);
$fuel = htmlspecialchars($_POST['fuel']);
$drive = htmlspecialchars($_POST['drive']);
$doors = htmlspecialchars($_POST['doors']);
$description = htmlspecialchars($_POST['description']);
$target = "images/default.jpg";
$msg = "";
if (!empty($_FILES['fisier']['name'])) {
$target = "images/";
$target = $target . basename($_FILES['fisier']['name']);
$file_size = $_FILES['fisier']['size'];
$file_type = $_FILES['fisier']['type'];
$ok = 1;
if ($file_size > 2048000) {
echo "Too large";
$ok = 0;
}
if ($file_type == "application/octet-stream") {
echo "no PHP";
$ok = 0;
}
if ($ok == 0) {
echo "No file saved";
} else {
if (!move_uploaded_file($_FILES['fisier']['tmp_name'],$target)) {
$target = "images/default.jpg";
$msg = "No file saved. ";
}
}
}
require_once("mysql_connect.php");
$sql = "INSERT INTO astonmartin VALUES('','$year','$make','$model','$engine','$mileage','$exterior','$interior','$transmission','$body','$fuel','$drive','$doors','$description','$target','$target2','$target3','$target4','$target5','$target6')";
mysql_query($sql) or die(mysql_error());
$msg .= "";
header("Location: add_user.php?msg=$msg");
} else {
$error = "Complete form";
}
}
?>
I think you need first this function assoc, here: multidimensional for loops in php
And continue;
<?php
$allowed_types = array(
'image/gif',
'image/jpeg',
// add your mime types more
);
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND ...
// that gives an associative array
// i think it's more handy in your case
$files = assoc($_FILES['fisier']);
// now you have a files like
// tmp_name => d:\tmp\abs123, name => cats.jpg, size => 128 ..
// tmp_name => d:\tmp\abs254, name => dogs.jpg, size => 211 ..
// ... more code here
// and here, remove this line
if (!empty($_FILES['fisier']['name'])) {
// put this. yes 6, cos you want 6 pics
if (count($files) == 6) {
// loop over files
foreach ($files as $i => $file) {
// create targets, securely
$targets[$i] =
'images/'. preg_replace('~[^\w\d\.]~i', '',
basename($file['name']));
// check some errors
if ($file['error'] == 0 && $file['size'] < 2048000
// check file type
&& in_array($file['type'], $allowed_types)) {
if (!move_uploaded_file(
$file['tmp_name'], 'images/'. $file['name'])) {
$targets[$i] = 'images/default.jpg';
// collect messages
$messages[] = $file['name'] . ' not saved!';
}
}
}
}
// and creating target 1 2 3 ...
$targets_string = '';
if (!empty($targets)) {
// this provides: '$target', '$target2', '$target3' ...
$targets_string = "'". join("', '", $targets) ."'";
}
// ... more code here
// and sql part
$sql = "INSERT INTO astonmartin VALUES('', '$year', '$make', ..."
// add target string
. "'$description', $targets_string";
// ... more code here
// msg part
$msg = empty($messages) ? '' : join('', $messages);
header("Location: add_user.php?msg=$msg");
?>

Categories