简体   繁体   English

我如何检查输入数组字段类型为空的文件是否未上传

[英]How can i check if input array filed type file empty doesn't upload

How can i check array input type file is empty before upload data in database. 在数据库中上传数据之前,如何检查数组输入类型文件是否为空。 if have one empty show anything that user understand and don't updata data. 如果有一个空白,则显示用户可以理解的任何内容,而不更新数据。

This is example code html 这是示例代码html

 <h3>Extra profile information</h3>
 <table class="form-table">
     <tr>
     <th><label for="Upload">Upload</label></th>
     <td>
        <form action="" method="post">
        <input name="profile_photo[]" type="file"  value="" />
        <input name="profile_photo[]" type="file"  value="" />
        <input name="profile_photo[]" type="file"  value="" />
        <br/>
    </form>
     </td>
 </table>

I used to use $x=$_GET['profile_photo']; 我曾经使用$ x = $ _ GET ['profile_photo']; and echo $x; 并回显$ x; before upload to database and it return empty or null. 在上载到数据库之前,它返回空或null。

if (!empty($_FILES) && is_array($_FILES)) {

  // you have files
}
$x=$_FILES['profile_photo']['name']; 

使用此代码

Just run a for loop on the post data and verify 只需在发布数据上运行for循环并验证

$error = "";
$emptyFiles="";
$i=0;
foreach ($_FILES['profile_photo'] as $name) {
   if (isset($name['name']) && $name['name']!="") {
       $error.="";
   } else {
       $error.= "yes";
       $emptyFiles.=$_FILES['profile_photo'][$i];
   }
    $i++;
}

Then use 然后使用

$error and $emptyFiles string to get which are empty fields and which are not. $ error和$ emptyFiles字符串获取哪些是空字段,哪些不是。

You can also validate inputs by javascript before submission 您还可以在提交之前通过javascript验证输入

html: HTML:

<form action="" method="post" onsubmit="return validateInputs();">
    <input name="profile_photo[]" type="file"  value="" />
    <input name="profile_photo[]" type="file"  value="" />
    <input name="profile_photo[]" type="file"  value="" />
    <input type="submit" />
</form>

javascript: JavaScript的:

validateInputs = function() {    
    inputs = document.getElementsByName('profile_photo[]');
    for (var ind in inputs){
        if (inputs[ind].value=="") {
            alert("validation failed");
            return false;
        }
    }         
}

in javascript/jquery 在javascript / jquery中

var file = $(".profile_photo").map(function(){return $(this).val();}).get();


for(var i=0; i<file.length; i++){
   if( file[i] == ""){
     alert("Please select file");
     return false;
   }
}

in PHP 在PHP中

if( $_FILES['profile_photo']['error'] != 0 ){
   // code to handle if there is no file selected
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM