Here is the code I am using for multiple image upload for every entry in the database; id, image, name, date. By using this code, the image name is inserting correctly but I have a problem with the name field. I want to insert the name using $product_name= $_POST['pro_name']; but it only inserts 'array' in name field.
<?php
include('../config.php');
if (isset($_POST['submit'])) {
$product_name = $_POST['pro_name'];
$j = 0; // Variable for indexing uploaded image.
$target_path = "uploads/"; // Declaring Path for uploaded images.
for ($i = 0; $i < count($_FILES['file']['name']) && $product_name < count($product_name); $i++) {
// Loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_extension = end($ext); // Store extensions in the variable.
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1]; // Set the target path with a new name of image.
$j = $j + 1; // Increment the number of uploaded images according to the files in array.
if (($_FILES["file"]["size"][$i] < 100000000) // Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
$finel_name = explode('/', $target_path);
$image_name_final = $finel_name[1];
$jajsj = "insert into spec_product set image='$image_name_final', name='$product_name'";
$janson = mysql_query($jajsj) or die(mysql_error());
// If file moved to uploads folder.
echo $j . ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { // If File Was Not Moved.
echo $j . ').<span id="error">please try again!.</span><br/><br/>';
}
} else { // If File Size And File Type Was Incorrect.
echo $j . ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
The value is inserting as array because the variable $product_name is not a string but an array. Whenever an array is used where a string was expected e.g.: concatenation of a string or in your case the query statment: insert into spec_product set image='$image_name_final', name='$product_name'"; PHP will automatically convert the array into its default string value "Array".
Make sure that $product_name is not an array but a string which contains name of the product you want to insert in the table.
Regards,
Nitin Thakur
replace in your code
for ($i = 0; $i < count($_FILES['file']['name']); $i++)
{
and add this before your query execute
$product_name_final= $product_name[$i];
Related
So I have created a small script that allows a user to upload multiple images of their car. I then process these images and store the file path in a database, and create a folder to store the images in, inside my 'vehicleImages' folder. I keep running into a problem though, so as you can see I check to see if the folder exists and if it doesn't I create one. Then the images get processed and in theory should be stored inside that folder.
The problem i'm running into is, it creates the folder like it should e.g. XX00VVV. But instead of storing the images inside 'vehcileImages/XX00VVV' it stores the images inside 'vehicleImages' not inside the correct folder. I've checked the server and the folder 'XX00VVV' is definetly being created but for some reason the images aren't being stored inside. I think it's where I change the target path but I can't figure out why. Can someone give me a few pointers/hints as to where I've gone wrong please?
$imagePath = "../../images/vehicleImages/".$vehicleReg;
$fileName = $vehicleReg;
if (!file_exists($imagePath)) {
mkdir($imagePath, 0777, true);
}
//Image Upload Section
$j = 0; //Variable for indexing uploaded image
$target_path = $imagePath; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) { //loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i])); //explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path.md5(uniqid()).
".".$ext[count($ext) - 1]; //set the target path with a new name of image
$j = $j + 1; //increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) { //if file moved to uploads folder
echo $j.
').<span id="noerror">Image Uploaded Successfully!.</span><br/><br/>';
} else { //if file was not moved.
echo $j.
').<span id="error">Please Try Again!.</span><br/><br/>';
}
} else { //if file size and file type was incorrect.
echo $j.
').<span id="error">***Invalid File Size or Type***</span><br/><br/>';
}
}
//End Image Upload Section
Image of Website Directory
so the problem is in first line in your code $imagePath
$imagePath = "../../images/vehicleImages/".$vehicleReg;
try to add ."/" to the end of line
like this:
$imagePath = "../../images/vehicleImages/".$vehicleReg."/";
the explain of the solution is:
when you didn't add / in the end of path, you make it merged with filename , eg XX00VVVfilenam.png
I am working on a script that uploads multiple images and saves the path to database to fetch the images in each record separately. The images are uploaded well but the image name in the database are stored in the following format uploads/image_name.png which should be actually just image_name.png. Moreover when I upload multiple images a separate record is created in the database for each image. I want to display them in the same field. Here is the code I am using to upload the file to the database using php.
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$img = implode('',$_FILES['file']['name']);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];
$title = (!empty($_POST['ad_title']))?$_POST['ad_title']:null;
$cat = (!empty($_POST['ad_cat']))?$_POST['ad_cat']:null;
$des = (!empty($_POST['ad_des']))?$_POST['ad_des']:null;
$name = (!empty($_POST['ad_name']))?$_POST['ad_name']:null;
$email = (!empty($_POST['ad_email']))?$_POST['ad_email']:null;
$phone = (!empty($_POST['ad_phone']))?$_POST['ad_phone']:null;
$state = (!empty($_POST['ad_state']))?$_POST['ad_state']:null;
//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 1024000) //Approx. 1mb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
$sql = "INSERT INTO ad_posting(img_name, ad_title, ad_cat, ad_des, ad_name, ad_email, ad_phone, ad_state)VALUES('$target_path', '$title','$cat','$des','$name','$email','$phone','$state')";
$frc = mysql_query($sql);
if ($frc){
echo "Success";
}else{
echo "Not Successful";
}
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
This is the javascript code i m using.
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
What is the error I am making? Please help me out solve the query.
from uploads/image_name.png to image_name.png.
$filename = 'uploads/image_name.png';
basename($filename);
in your sql
$sql = "INSERT INTO ad_posting(img_name, ad_title, ad_cat, ad_des, ad_name, ad_email, ad_phone, ad_state)VALUES('$target_path', '$title','$cat','$des','$name','$email','$phone','$state')";
if $target_path have the vale uploads/image_name.png then
$target_path = basename($target_path);
if you want the name of all images in the same field you can use implode().
I'm uploading multiple files.
Main function works fine, but I have to change the names of uploading files Like:
name1.jpg, name2.jps, name3.jpg, ...
$i = 1;
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/name'.$i++.'.'.$extension)){
echo '{"status":"success"}';
exit;
}
Number $i should grow with amount of uploaded files.
I hope that explained it correctly.
You need a loop:
if(isset($_FILES['files'])){
$name_array = $_FILES['files']['name'];
$tmp_name_array = $_FILES['files']['tmp_name'];
// Number of files
$count_tmp_name_array = count($tmp_name_array);
// We define the static final name for uploaded files (in the loop we will add an number to the end)
$static_final_name = "name";
for($i = 0; $i < $count_tmp_name_array; $i++){
// Get extension of current file
$extension = pathinfo($name_array[$i] , PATHINFO_EXTENSION);
// Pay attention to $static_final_name
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$static_final_name.$i.".".$extension)){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
The Script:
$desired_width = 110;
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1];
$target_path = $target_path . $new_image_name;//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
$tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())";
$tqr = mysqli_query($dbc, $tqs);
/*
* At this spot right here with the variable "$new_image_name".
*/
// Goes over to create the thumbnail images.
$src = $target_path;
$dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/" . $new_image_name;
make_thumb($src, $dest, $desired_width);
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
This script also uses java script for multiple image upload.
I am looking to select the ID numbers from the ID column of the last uploaded images.
It should store the ID numbers inside an array.
For Example:
// It stores the ID numbers of the hashtags inside an array.
$hashlist = join ("','", array_map(array($dbc,'real_escape_string'),$hashtags));
$tqs = "SELECT `id` FROM `hashtags` WHERE `hashtag` IN ('$hashlist')";
$tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));
$fetch_array = array();
while($row = mysqli_fetch_array($tqr)){
$fetch_array[] = $row['id'];
}
// This implodes the array with the ID numbers into a string.
$fetch_array = implode(", ", $fetch_array);
// The previously created thread gets its "hashtag_id" column updated with the hashtag ID numbers.
// The hashtag ID numbers are separated by commas.
$tqs = "UPDATE thread SET `hashtag_id` = '" . $fetch_array . "' WHERE `id` = '" . $the_insert_id . "'";
$tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));
I use this script to select the ID numbers from the hashtags table. It then stores them inside an array, then I use the "explode()" function on the array, after that the script stores the ID numbers inside of a column in the table "hashtags".
If I use this example on the scenario with the images then I am getting errors.
For example:
Warning: array_map(): Argument #2 should be an array in C:\xampp\htdocs\gallerysite\multiple_image_upload\upload.php on line 52
Warning: join(): Invalid arguments passed in C:\xampp\htdocs\gallerysite\multiple_image_upload\upload.php on line 52
Array ( )
I am looking to solve the scenario with the images in this manner too.
The ID numbers of the last uploaded image should get selected, then get stored inside an array, so I can insert the ID numbers (separated by commas) inside a column of a table.
Any suggestions on how to do this?
I have a form, upon submission, it will create a new directory, all images submitted along with the form will be upload in the said directory.
this is the shortened code.
mkdir('uploads/'.$name, 0777, true); //create directory
$count = count($_FILES['images']['tmp_name']); //count all uploaded files
for ($i=0; $i<$count; $i++)
{
//formatting
$file = $_FILES['images']['name'][$i];
$filename = strtolower($file);
$random = rand(0, 999); //Random number to be added to name.
$newfile = $random.$filename; //new file name
//upload
if (move_uploaded_file($newfile, "uploads/".$name."/".$newfile))
{
echo "uploaded";
} else {
echo " failed";
}
}
if i echo the directory echo "upload to =" . $teamdir."/".$newfile;
it shows the correct path /uploads/john/567banner_0.jpg
but the image aren't being uploaded.
bool move_uploaded_file ( string $filename , string $destination )
Your first parameter has to be the source so you have to give it the temp name assigned
by php.
In your case : $_FILES['images']['tmp_name'][$i]
I feel you should add
$_SERVER['DOCUMENT_ROOT'].'/path/to/uploads/
in image destination path