Hi there I want to make a function for me to able upload a multiple image in one submission below are my code structure:
Try something like this:
...
$images = array();
foreach (array('image1', 'image2', 'image3') as $name) {
$images[$name] = new stdClass();
$images[$name]->fileName = $_FILES[$name]['name'];
$images[$name]->tmpName = $_FILES[$name]['tmp_name'];
$images[$name]->fileSize = $_FILES[$name]['size'];
$images[$name]->fileType = $_FILES[$name]['type'];
$images[$name]->path = $uploadDir . $images[$name]->fileName;
$result = move_uploaded_file($images[$name]->tmpName, $images[$name]->path);
if (!$result) {
echo "Error uploading";
exit;
}
$images[$name]->sql = mysql_real_escape_string($images[$name]->path);
}
$sql="INSERT INTO picture (image1, image2, image3) VALUES ({$images['image1']},{$images['image2']},{$images['image3']})";
...
Here is the code to multiple upload image. You can upload more than 3 images.
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>Image1 :<input name="image[]" type="file" /></p>
<p>Image2 :<input name="image[]" type="file" /></p>
<p>Image3 :<input name="image[]" type="file" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include('configdb.php');
$uploadDir = 'upload/';
if(isset($_POST['submit'])) {
$image = array();
foreach($_FILES['image']['name'] as $index => $name) {
if($_FILES['image']['error'][$index] == 4) {
continue;
}
if($_FILES['image']['error'][$index] == 0) {
$fileName = $_FILES['image']['name'][$index];
$tmpName = $_FILES['image']['tmp_name'][$index];
$fileSize = $_FILES['image']['size'][$index];
$fileType = $_FILES['image']['type'][$index];
if(($fileType == "image/gif" ||
$fileType == "image/jpeg" ||
$fileType == "image/pjpeg" ||
$fileType == "image/png" ||
$fileType == "image/x-png") &&
$fileSize < 500000) {
$imagePath = $uploadDir . $fileName;
$result = @move_uploaded_file($tmpName, $imagePath);
if (!$result) {
echo "Error uploading";
exit;
}
$image[] = $imagePath;
}
}
}
// Save images to database
$nbImage = count($image);
if($nbImage) {
$sql = "INSERT INTO picture (image1, image2, image3) VALUES (";
for($i=0; $i<$nbImage; $i++) {
if($i) $sql .= ",";
$sql .= "\"".$image[$i]."\"";
}
$sql .= ")";
@mysql_query($sql);
}
}
?>
Note: you should test the type and the size of image before upload it because of the security.