输入标签未在某些设备中选择多个图像

Input tag is not selecting multiple images in some devices

提问人:Nandini Srivastava 提问时间:9/12/2023 最后编辑:Nandini Srivastava 更新时间:9/12/2023 访问量:30

问:

我创建了一个网站,用户可以在其中上传带有图像的问题。为此,我使用带有“multiple”属性的输入标签来选择多个图像并使用 PHP 将其上传到数据库中。但是在某些设备中,或者可能是浏览器,它不会选择多个图像或将其存储在数据库中。在这些设备中,它只存储单个图像。 我正在提供我的输入标签代码。如果需要,我可以提供带有数据库连接代码的整页代码。

你能告诉我解决方案吗?

<input type="file" accept="image/png , image/jpeg" multiple id="quesImgSelect" onchange="quesPreview()" class="imgBtn" name="quesDoc[]">

尝试上传多张图片,但在某些设备中不起作用。

我的页面的完整代码在这里......

session_start();
//include "config.php";

?>
<!-- Uploading code starts -->

<?php
include "config.php";
if(isset($_POST["submit"])){
  // print_r("expression");exit()
if (empty($_FILES['ansDoc']['name'][0])) {

$ansImgText = "no" ;
}else{
   
$ansImgText = "yes" ; 
  
  };


  if (empty($_FILES['quesDoc']['name'][0])) {

    $quesImgText = "no" ;
    }else{
       
    $quesImgText = "yes" ; 
      
      };


  $userId = $_SESSION['id'];

$question ="no" ;
$exam =$_GET['exam'] ;
$year =$_GET['year'] ;
$ansText =(mysqli_real_escape_string($conn,$_POST['ansText'])) ;
$quesText =(mysqli_real_escape_string($conn,$_POST['quesText'])) ;
$subject =(mysqli_real_escape_string($conn,$_POST['sub'])) ;
$lang =(mysqli_real_escape_string($conn,$_POST['lang'])) ;
if($_POST['lang'] == ""){
    $topic ="no" ;
}else{
    $topic =(mysqli_real_escape_string($conn,$_POST['topic'])) ;
}

$approval ="no" ;
$solution ="no" ;
$paperId =$_GET['id'] ;

//echo $paperId.$year;
date_default_timezone_set('Asia/Kolkata');
$date=date("y-m-d");

$sql="INSERT INTO `questions` (`question`, `userId`, `date`, `subject`, `lang`, `topic`, `approval`, `solution`, `exam`, `year`, `paperId`,`quesImg`,`ansImg`) VALUES    
('{$quesText}', '{$userId}', '{$date}','{$subject}','{$lang}', '{$topic}','{$approval}','{$ansText}','{$exam}','{$year}','{$paperId}','{$quesImgText}','{$ansImgText}')";
 
$result=mysqli_query($conn,$sql) or die("result failed1");

  
 $idd= $conn->insert_id; 

//echo $idd;

// print_r($_FILES['quesDoc']);exit();

foreach($_FILES['quesDoc']['name'] as $key=>$val){
    
$filename = rand().".jpg";
// 3,000,000
// print_r($_FILES['quesDoc']['size'][$key]);exit();
$file_size = $_FILES['quesDoc']['size'][$key];
//if($file_size < 3000000){
move_uploaded_file($_FILES['quesDoc']['tmp_name'][$key],"quesImg/".$filename);

$sql2="INSERT INTO `quesimg` (`qId`, `image`,`paperId`) VALUES ('{$idd}','{$filename}','{$paperId}')";

$result2=mysqli_query($conn,$sql2) or die("result failed2");
//}
   // echo "Error: " . mysqli_error($conn);

//echo "added";
}

//if (!empty($_FILES['ansDoc']['name'][0])) {

foreach($_FILES['ansDoc']['name'] as $key=>$val){
    
    $filename2 = rand().".jpg";
    move_uploaded_file($_FILES['ansDoc']['tmp_name'][$key],"ansImg/".$filename2);
    
    $sql3="INSERT INTO `solutionimg` (`qId`, `image`,`paperId`) VALUES ('{$idd}','{$filename2}','{$paperId}')";
    
    $result3=mysqli_query($conn,$sql3) or die("result failed3");
    
       // echo "Error: " . mysqli_error($conn);
    
   // echo "added";

  //  $id = mysqli_real_escape_string($conn,$_POST['id']);

$sql4 = "SELECT * FROM `question_paper` WHERE `id` = $paperId";
$result4=mysqli_query($conn,$sql4) or die("result failed4");
if(mysqli_num_rows($result4)>0){
    while($row=mysqli_fetch_assoc($result4)){
       $total = $row['total'] ;
       $newTotal = $total + 1;
        
       // echo $newRented;
    $sql5="UPDATE `question_paper` SET `total` = $newTotal  WHERE `question_paper`.`id` = $paperId";

   
    $result5=mysqli_query($conn,$sql5) or die("result failed5"); 
          
   // echo "updated";
    }


    
    
}


$sql6 = "SELECT * FROM `ZZZ_teacherProfile` WHERE `id` = $userId";
$result6=mysqli_query($conn,$sql6) or die("result failed");
if(mysqli_num_rows($result6)>0){
    while($row=mysqli_fetch_assoc($result6)){
       $total = $row['ques'] ;
       $newTotal = $total + 1;
        
       // echo $newRented;
    $sql7="UPDATE `ZZZ_teacherProfile` SET `ques` = $newTotal  WHERE `ZZZ_teacherProfile`.`id` = $userId";

   
    $result7=mysqli_query($conn,$sql7) or die("result failed6"); 
          
   // echo "updated";
    }


    
    
}




    echo "<script>";
    echo  "alert('Question added successfully.')";
      echo  "</script>";

    }


}
?>

<!-- Uploading code ends -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add question</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="addQuestionPage.css">

    
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
</head>
<body>
<div id="container">


<div id="backBtnContainer">
    <a href="adminPaperDetailPage.php?id=<?php echo $_GET['id'];?>">Back</a>
</div>
        
        <form  action="<?php $_SERVER['PHP_SELF'] ?>" method="POST" id="form" enctype="multipart/form-data">


        <label for="language">Select language</label>

        <select name="lang" id="language">
<option value="english">English</option>
    <option value="hindi">Hindi</option>

</select>

<label for="subjectsDropdown">Select subject</label>
  <select id="subjectsDropdown" onchange="loadTopics()" name="sub">

  <?php
    include "config.php";
  
       $sql="SELECT * FROM `$db`.`ZZ_subject` ORDER BY `name` ASC";
       $result=mysqli_query($conn,$sql);
   
       if(mysqli_num_rows($result)>0){
           while($row=mysqli_fetch_array($result)){
               $data['id']=$row['0'];
            $data['subject']= $row['1'];
          
            ?>
         
        <option value="<?php   echo $row['name'];  ?>"> <?php   echo $row['name'];  ?></option>

  <?php
           }

          
        }else{ 
            echo "No category added";

        }
        ?>
 
</select>
<label for="topicsDropdown">Select topic</label>

<!-- Second Dropdown (Topics) -->
<select id="topicsDropdown" name="topic">
 
</select>


<textarea rows="10"  placeholder="Enter question" class="inputBox" id="quesText" name="quesText"></textarea>
<input type="file" accept="image/*" multiple id="quesImgSelect" onchange="quesPreview()" class="imgBtn" name="quesDoc[]">
<label for="quesImgSelect" class="ImgLabel"> <i class="fa fa-upload" aria-hidden="true"></i> Upload question image Should be less than 3mb </label>
<p id="quesImgCount" >No file choosen</p>
<div id="quesImage" class="imgDiv"></div>

<textarea rows="10" cols="60" placeholder="Enter answer" class="inputBox" id="answerText" name="ansText"></textarea>
<input type="file" accept="image/png , image/jpeg" multiple="multiple" id="ansImageSelect" class="imgBtn" onchange="ansPreview()" name="ansDoc[]">
<label for="ansImageSelect" class="ImgLabel"> <i class="fa fa-upload" aria-hidden="true"></i> Upload answer image Should be less than 3mb</label>

<p id="ansImgCount" >No file choosen</p>
<div id="ansImage" class="imgDiv"></div>

<input type="submit" value="SAVE" id="submit" name="submit">



</form>



<script>
function loadTopics() {
  // Get the selected subject from the first dropdown
  let selectedSubject = document.getElementById("subjectsDropdown").value;

  // Get the second dropdown element
  let topicsDropdown = document.getElementById("topicsDropdown");

  // Clear the existing options in the second dropdown
  topicsDropdown.innerHTML ;

  // Use AJAX to fetch topics for the selected subject from the database
  // You can use any AJAX library like jQuery or fetch API
  fetch('G_getTopic.php?subject_id=' + selectedSubject)
    .then(response => response.json())
    .then(data => {
        topicsDropdown.innerHTML = '';
      // Check if there are topics available for the selected subject
      if (data.length > 0) {
        data.forEach(topic => {
          addTopicOption(topic.topic_name, topic.topic_name);
        });
      } else {
        addTopicOption('no', 'No topic added');
      }
    })
    .catch(error => {
      console.error('Error fetching topics: ', error);
    });
}

// Helper function to add options to the second dropdown
function addTopicOption(value, text) {
  let topicsDropdown = document.getElementById("topicsDropdown");
  let option = document.createElement("option");
  option.value = value;
  option.text = text;
  topicsDropdown.appendChild(option);
}


//Images code ---------------------------------------------------------------


let quesInput = document.getElementById("quesImgSelect");
let ansInput = document.getElementById("ansImageSelect");

let quesCountView = document.getElementById("quesImgCount");
let ansCountView = document.getElementById("ansImgCount");

let quesImageDiv = document.getElementById("quesImage");
let ansImageDiv = document.getElementById("ansImage");


function quesPreview(){
    quesCountView.textContent = `${quesInput.files.length} Files selected`;

    for(i of quesInput.files){
        let reader = new FileReader();
        let figure = document.createElement("figure");
        let figCap = document.createElement("figCaption");

        figCap.innerText = i.name;
        figure.appendChild(figCap);
        reader.onload=()=>{
            let img = document.createElement("img");
            img.setAttribute("src",reader.result);
            figure.insertBefore(img,figCap);
        }
        quesImageDiv.appendChild(figure);
        reader.readAsDataURL(i);
    }
}


function ansPreview(){
    ansCountView.textContent = `${ansInput.files.length} Files selected`;

    for(i of ansInput.files){
        let reader = new FileReader();
        let figure = document.createElement("figure");
        let figCap = document.createElement("figCaption");

        figCap.innerText = i.name;
        figure.appendChild(figCap);
        reader.onload=()=>{
            let img = document.createElement("img");
            img.setAttribute("src",reader.result);
            figure.insertBefore(img,figCap);
        }
        ansImageDiv.appendChild(figure);
        reader.readAsDataURL(i);
    }
}
</script>

</div>
</body>
</html>```
php html mysql web 输入

评论

0赞 ADyson 9/12/2023
您需要提供该问题的最小可重现示例。另请参阅如何提问。您可以编辑您的帖子。
0赞 ADyson 9/12/2023
包含足够的代码来重现问题(但仅此而已!)是有意义的,并且还描述了您的测试中哪些设备/浏览器始终存在问题。
0赞 nice_dev 9/12/2023
你能写吗?multiple="multiple"
0赞 Nandini Srivastava 9/12/2023
我已经尝试过了,但仍然不起作用
1赞 ADyson 9/12/2023
@nice_dev也许是这样,但值得庆幸的是,那些完全无视规格的狂野西部时代早已一去不复返了。如果 OP 仍在尝试在 IE 中完成这项工作,那么在 2023 年,这将是一个非常不寻常的情况,他们需要提及。(无论如何,正如我上面所说,他们需要告诉我们更多关于他们在何时何地失败的观察结果的信息。

答: 暂无答案