ianhaney50 Posted October 5, 2014 Share Posted October 5, 2014 Hi I am developing a website for fun to play around with, like a little fun project and am trying to work out how to upload multiple images that stores the filename in the database and the actual file on the server I have managed to get it working if I upload just one image but can't work it out for multiple images Can anyone point me in the right direction or advise where I need to adjust for multiple images upload I know on the html form on the input tag needs to have multiple and then the name in the input tag be image[] but is as far as I get, it's the PHP I get stuck on The html for the form is below <form action="private-add-insert.php" method="post" enctype="multipart/form-data"> Car Make: <input type="text" name="make"> Car Model: <input type="text" name="model"> Exterior Colour: <input type="text" name="exteriorcolour"> Engine Size: <input type="text" name="enginesize"> Fuel Type: <input type="text" name="fueltype"> Year Registered: <input type="text" name="yearregistered"> Transmission: <input type="text" name="transmission"> Mileage: <input type="text" name="mileage"> Number of Doors: <input type="text" name="nodoors"> Body Style: <input type="text" name="bodystyle"> Price: <input type="text" name="price"> <br> <label>Upload Images</label> <input type="file" name="image[]" multiple/> <br /> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> <br /> <input type="submit" value="Submit Listing"> </form> Below is the PHP coding that processes the html form <?php ini_set('display_startup_errors',1); ini_set('display_errors',1); error_reporting(-1); ?> <?php // Start a session for error reporting session_start(); // Call our connection file require("includes/conn.php"); // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "private-listing-images/"; // Get our POSTed variables $make = $_POST['make']; $model = $_POST['model']; $exteriorcolour = $_POST['exteriorcolour']; $enginesize = $_POST['enginesize']; $fueltype = $_POST['fueltype']; $yearregistered = $_POST['yearregistered']; $transmission = $_POST['transmission']; $mileage = $_POST['mileage']; $nodoors = $_POST['nodoors']; $bodystyle = $_POST['bodystyle']; $price = $_POST['price']; $image = $_FILES['image']; // Sanitize our inputs $make = mysql_real_escape_string($make); $model = mysql_real_escape_string($model); $exteriorcolour = mysql_real_escape_string($exteriorcolour); $enginesize = mysql_real_escape_string($enginesize); $fueltype = mysql_real_escape_string($fueltype); $yearregistered = mysql_real_escape_string($yearregistered); $transmission = mysql_real_escape_string($transmission); $mileage = mysql_real_escape_string($mileage); $nodoors = mysql_real_escape_string($nodoors); $bodystyle = mysql_real_escape_string($bodystyle); $price = mysql_real_escape_string($price); $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved do // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, bmp or png"; header("Location: private-add-listing.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into privatelistings (make, model, exteriorcolour, enginesize, fueltype, yearregistered, transmission, mileage, nodoors, bodystyle, price, filename) values ('$make', '$model', '$exteriorcolour', '$enginesize', '$fueltype', '$yearregistered', '$transmission', '$mileage', '$nodoors', '$bodystyle', '$price', '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: private-add-listing-successfully.php?msg=Listing Added successfully"); exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: private-add-listing.php"); exit; } ?> I know the coding needs updating to mysqli and prevent sql injections but want to get it working first and then will do them parts Thank you in advance Kind regards Ian Quote Link to comment https://forums.phpfreaks.com/topic/291453-multiple-images-upload-issue/ Share on other sites More sharing options...
Ch0cu3r Posted October 5, 2014 Share Posted October 5, 2014 I know on the html form on the input tag needs to have multiple and then the name in the input tag be image[] but is as far as I get, it's the PHP I get stuck on When you do that the corresponding superglobal variable will be an array containing the fields values. So you will need to loop over the array to get each value for each field. Example starting code if(is_array($_FILE['image'])) { // loop over each uploaded image foreach($_FILE['image'] as $image) { // add your code here for handling file upload, example starting code if (!is_valid_type($image['name'])) { // not a valid file, issue an error } if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // add the image to database } else { // problem with moving file } } } Note as you are uploading multiple images you will need to reconsider your database structure. It is a bad database design if added all the images into the same row. You will be better of inserting the uploaded images for the product into a separate table. The relationship between these table will be one to many (as a product can have multiple images). You'd use the products id as the foreign key in the images table. When fetching the data for product from the table you'd use a JOIN to retrieve the images that correspond to the image. If what I said above makes no sense. Read this article to get a better understanding. Quote Link to comment https://forums.phpfreaks.com/topic/291453-multiple-images-upload-issue/#findComment-1492812 Share on other sites More sharing options...
ianhaney50 Posted October 5, 2014 Author Share Posted October 5, 2014 Hi Ch0cu3r Thank you for the reply I have got it sort of working now, the image filenames stored in the database and the actual images are stored on the server Only thing it is not doing is uploading the images to the server The html coding is below <form action="private-add-insert.php" method="post" enctype="multipart/form-data"> Car Make: <input type="text" name="make"> Car Model: <input type="text" name="model"> Exterior Colour: <input type="text" name="exteriorcolour"> Engine Size: <input type="text" name="enginesize"> Fuel Type: <input type="text" name="fueltype"> Year Registered: <input type="text" name="yearregistered"> Transmission: <input type="text" name="transmission"> Mileage: <input type="text" name="mileage"> Number of Doors: <input type="text" name="nodoors"> Body Style: <input type="text" name="bodystyle"> Price: <input type="text" name="price"> <br> <label>Photo1</label> <input type='hidden' name='size' value='350000'><input type='file' name='photo[]'> <br /> <label>Photo2</label> <input type='hidden' name='size' value='350000'><input type='file' name='photo[]'> <br /> <input type="submit" value="Submit Listing"> </form> The PHP coding for the form is below <?php ini_set('display_startup_errors',1); ini_set('display_errors',1); error_reporting(-1); // Start a session for error reporting session_start(); $conn = mysql_connect('host','username','password', 3306) or die(mysql_error()); $db_name = mysql_select_db('databasename') or die(mysql_error()); //This is the directory where images will be saved $target = "private-listing-images/"; //This gets all the other information from the form $make = $_POST['make']; $model = $_POST['model']; $exteriorcolour = $_POST['exteriorcolour']; $enginesize = $_POST['enginesize']; $fueltype = $_POST['fueltype']; $yearregistered = $_POST['yearregistered']; $transmission = $_POST['transmission']; $mileage = $_POST['mileage']; $nodoors = $_POST['nodoors']; $bodystyle = $_POST['bodystyle']; $price = $_POST['price']; // use static values in that case $pic1= basename($_FILES['photo']['name'][0]); $pic2= basename($_FILES['photo']['name'][1]); if(!empty($_FILES['photo']['tmp_name'])) { // prepare insert query statement $sql = "INSERT INTO privatelistings (make,model,exteriorcolour,enginesize,fueltype,yearregistered,transmission,mileage,nodoors,bodystyle,price,photo,photo1) VALUES ('$make', '$model', '$exteriorcolour', '$enginesize', '$fueltype', '$yearregistered', '$transmission', '$mileage', '$nodoors', '$bodystyle', '$price', '$pic1', '$pic2')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: private-listing-added-successfully.php?msg=Listing Added successfully"); exit; // Number of uploaded files $num_files = count($_FILES['photo']['tmp_name']); /** loop through the array of files ***/ for($i=0; $i < $num_files;$i++) { // check if there is a file in the array if(!is_uploaded_file($_FILES['photo']['tmp_name'][$i])) { $messages[] = 'No file uploaded'; } else { // move the file to the specified dir if(move_uploaded_file($_FILES['photo']['tmp_name'][$i],$target.'/'.$_FILES['photo']['name'][$i])) { $messages[] = $_FILES['photo']['name'][$i].' uploaded'; } else { // an error message $messages[] = 'Uploading '.$_FILES['photo']['name'][$i].' Failed'; } } } echo '<pre>'.print_r($sql, true).'</pre>'; echo '<pre>'.print_r($messages, 1).'</pre>'; // execute query... $result = mysql_query($sql) or die(mysql_error()); } ?> I have heard about JOIN so if I store the data in the one table and the images in another would it be like the following listingsdata JOIN listingimages or is LEFT JOIN better how would the SELECT work, would it be something like select name, price, photo1, photo2 FROM listingsdata JOIN listingimages am I close or could you see where I am going wrong as to the images not being moved/uploaded onto the server and only storing the filenames in the database Quote Link to comment https://forums.phpfreaks.com/topic/291453-multiple-images-upload-issue/#findComment-1492818 Share on other sites More sharing options...
jcbones Posted October 5, 2014 Share Posted October 5, 2014 Make sure your storage folder has the right permissions, or the images will not be moved. AS far as JOINs go, the rule of thumb is a JOIN returns records that exist in both tables, but a LEFT JOIN returns all the results from the left table even if they have no corresponding result in the other table. Your image table should store one image per row, then you would join the data. SELECT d.name, d.price, i.photo FROM listingsdata AS d JOIN listingimages AS i ON d.id = i.data_id WHERE whateverSearched = 'blah' This all depends on foreign and primary keys of course. Quote Link to comment https://forums.phpfreaks.com/topic/291453-multiple-images-upload-issue/#findComment-1492829 Share on other sites More sharing options...
ianhaney50 Posted October 6, 2014 Author Share Posted October 6, 2014 Hi jcbones Thank you for the reply and help, appreciate it I checked the permissions and is set to write I will have a look at the JOIN WAY today just want to get the images uploaded to the server first and then will have a play with the JOIN I can only think it is do with this the following line / move the file to the specified dir if(move_uploaded_file($_FILES['photo']['tmp_name'][$i],$target.'/'.$_FILES['photo']['name'][$i])) Quote Link to comment https://forums.phpfreaks.com/topic/291453-multiple-images-upload-issue/#findComment-1492845 Share on other sites More sharing options...
ianhaney50 Posted October 6, 2014 Author Share Posted October 6, 2014 Sorry thought would post a update I got it working now, did not using JOIN for now but def will, just wanted to get it working first Quote Link to comment https://forums.phpfreaks.com/topic/291453-multiple-images-upload-issue/#findComment-1492865 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.