上传多个带描述的图片?

时间:2017-07-10 05:36:54

标签: php mysql arrays

是否可以在php中上传多个带有描述的图像?

enter image description here

这是我的代码:

if(isset($_FILES['files'])){
    $gn_id=$_POST['gn_id'];
    $date=date('Y-m-d');
    $errors= array();
    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_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }       
        $query="INSERT INTO `add_gallery` (`id`, `gn_id`, `photo`, `desc`, `date`) VALUES ('', '$gn_id', '$file_name', '$desc', '$date')";

        $desired_dir="gallery";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("../$desired_dir", 0700);     // Create directory if it does not exist
            }
            if(is_dir("../$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"../$desired_dir/".$file_name);
            }else{                                  // rename the file if another one exist
                $new_dir="../$desired_dir/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
         $qu=mysql_query($query);           
        }else{
                print_r($errors);
        }
    }   
}

1 个答案:

答案 0 :(得分:1)

您可以通过将描述值发布为数组来完成此任务。

<input name="description[]" value="First Image" />
<input name="description[]" value="Second Image"  />
<input name="description[]" value="Third Image" />
<input name="description[]" value="Fourth Image" />
<input name="description[]" value="Fifth Image" />

然后

$_POST['description'][0] == 'First Image'
$_POST['description'][3] == 'Fourth Image'

发布值后,您就可以进入foreach循环了。在循环中,您可以使用当前索引描述数组

获取当前图像描述
// Getting description values as arrays
$Description_Values = $_POST['description'];
// Below iteration counter
$Counter = 0;
// This is your foreach loop which you are using for images
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
// Getting Current Image Description
$current_image_description = $Description_Values[$Counter];
$Counter++;
}