它不会将数据插入到数据库中 [英] It is not inserting data into database

查看:109
本文介绍了它不会将数据插入到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据插入 Image_Question 表中。但它不会在 Image_Question 表中执行插入操作。



我得到两个错误:


  • 注意:未定义偏移量:0 ...在线305

  • 注意:未定义抵消:3在...在线305



以下是您可以使用的应用程式:应用程式



要使用应用程序查看正在发生的事情,请执行以下操作:
$ b

  • 添加问题按钮两次以追加两个文件输入

  • 现在每次上传一个文件,但要它是这样的。上传第1行文件输入中的文件,然后上传第2行中的文件,然后再上传第1行中的文件,最后上传第2行中的文件。


    以下是mysqli代码:

      //提前准备好您的报表
    $ questionsql =INSERT INTO Question(QuestionNo)VALUES(?);
    if(!$ insert = $ mysqli-> prepare($ questionsql)){
    //在此准备操作处理错误
    echo __LINE__。':'。$ mysqli->错误;

    $ b $ imagequestionsql =INSERT INTO Image_Question(ImageId,QuestionId)
    VALUES(?,?);
    $ b $ if(!$ insertimagequestion = $ mysqli-> prepare($ imagequestionsql)){
    //在这里准备操作处理错误
    echo __LINE__。':'。$ mysqli->误差;
    }

    //如果($ insert&& $ insertimagequestion){
    $ c = count($ _ POST)在继续处理
    之前确保两个预处理语句成功[ 'numQuestion']);
    $ question_ids = array(); ($ i = 0; $ i <$ c; $ i ++){
    $ questionNo = $ _POST ['numQuestion'] [$ i];

    ;

    $ insert-> bind_param(i,$ questionNo);

    $ insert-> execute();
    $ b $ if($ insert-> errno){
    //在这里处理查询错误
    echo __LINE__。':'。$ insert-> error;
    break 1;
    }

    $ questionId = $ mysqli-> insert_id;

    $ question_ids [$ questionNo] = $ questionId;
    }

    $ imgresults = $ _POST ['imgid'];
    foreach($ imgresults as $ imgid => $ imgvalue){
    $ image = $ imgvalue;
    $ imgquesid = $ question_ids [$ imgid]; // LINE 305其中错误是

    foreach($ imgvalue as $ image){
    $ insertimagequestion-> bind_param(ii,$ image,$ imgquesid);
    $ insertimagequestion-> execute();

    if($ insertimagequestion-> errno){
    //在这里处理查询错误
    echo __LINE__。':'。$ insertimagequestion-> error;
    break 2;
    }
    }
    }
    $ insertimagequestion-> close();
    $ insert-> close();
    }

    ?>

    下面是设置演示的代码:

     函数GetFormImageCount(){
    return $('。imageuploadform')。length + 1;
    }

    var qnum = 1;
    var qremain = 5;

    函数insertQuestion(form){

    if(qnum> 5)
    return;

    var $ tbody = $('#qandatbl_onthefly> tbody');
    var $ tr = $(< tr class ='optionAndAnswer'align ='center'>);
    var $ qid = $(< td width ='5%'class ='qid'>< / td>)。text(qnum);
    var $ image = $(< td width = '17%'class ='image'>< / td>);

    $('。num_questions')。each(function(){

    var $ this = $(this);

    var $ questionNumber ='('< input type ='hidden'class ='num_questionsRow'>)。attr('name',$ this.attr('name')+[])。attr('value', $ this.val());

    $ qid.append($ questionNumber);

    ++ qnum;
    $(。questionNum).text (qnum);
    $(。num_questions).val(qnum);

    --qremain;
    $(。questionRemain)。text(qremain);
    });
    $ b var $ fileImage = $(< form action ='imageupload.php'method ='post'enctype ='multipart / form-data'target ='upload_target_image'onsubmit ='return imageClickHandler(这个);'class ='imageuploadform'>+
    < p class ='imagef1_upload_form'>< label>+
    图片文件:< input name ='fileImage' type ='file'c​​lass ='fileImage'/>< / label>< br />< br />< label class ='imagelbl'>+
    < input type ='submit'name ='submitImageBtn'class ='sbtnimage'value ='Upload'/>< / label>+
    < p class ='imagef1_upload_process'> Loading ...< ;< img src ='Images / loader.gif'/>< / p>+
    < input type ='hidden'class ='numimage'name ='numimage' value ='+ GetFormImageCount()+'/>+
    < / p>< p class ='imagemsg'>< / p>< p class ='listImage'> ;< / p>+
    < iframe class = upload_target_image名称= upload_target_image SRC = /风格=宽度:0像素;高度:0像素;边界:0像素;固体; #FFF;>< / iframe中>< /形式>中);

    $ image.append($ fileImage);

    $ tr.append($ qid);
    $ tr.append($ image);
    $ tbody.append($ tr);
    }

    函数imageValidation(imageuploadform){
    var val = $(imageuploadform).find(。fileImage)。val();
    switch(val.substring(val.lastIndexOf('。')+ 1).toLowerCase()){
    case'gif':
    case'jpg':
    case 'jpeg':
    'pjpeg':
    'png':
    返回true;

    case'':
    $(imageuploadform).find(。fileImage)。val();
    alert(要上传图片,请选择图片文件);
    返回false;

    默认值:
    alert(上传图片,请选择图片文件);
    返回false;
    }
    返回false;


    函数htmlEncode(value){return $('< div />')。text(value).html(); }

    image(imageuploadform){
    $(imageuploadform).find('。imagef1_upload_process')。show()
    $(imageuploadform).find('。imagef1_upload_form' )。隐藏();
    $(imageuploadform).find('。imagemsg')。hide();
    sourceImageForm = imageuploadform;

    返回true;
    }

    var imagecounter = 0;

    function stopImageUpload(success,imageID,imagefilename){
    var result ='';
    imagecounter ++;

    if(success == 1){
    result ='< span class =imagemsg'+ imagecounter +'>成功上传文件< / span>;
    $('。hiddenimg')。eq(window.lastUploadImageIndex).append('< input type =textname =imgid []id ='+ imageID +'value ='+ imageID +'/>');
    $('。listImage')。eq(window.lastUploadImageIndex).append('< div> + htmlEncode(imagefilename)+'< button type =buttonclass =deletefileimagedata-imageID删除< / button>< br />< hr />< / div>< );


    $(sourceImageForm).find('。imagef1_upload_process')。hide();
    $(sourceImageForm).find('。imagemsg')。html(result);
    $(sourceImageForm).find('。imagemsg')。show();
    $(sourceImageForm).find(。fileImage)。replaceWith(< input type ='file'c​​lass ='fileImage'name ='fileImage'/>);
    $(sourceImageForm).find('。imagef1_upload_form')。show();


    var _imagecounter = imagecounter; (。click,function(event){
    jQuery.ajax()。
    $ b $('。listImage')。eq(window.lastUploadImageIndex).find(。deletefileimage)。 deleteimage.php?imagefilename =+ $(this).attr('data-image_file_name'))。done(function(data){
    $(。imagemsg+ _imagecounter).html(data);
    $)

    var buttonid = $(this).attr('value');
    $(this).parent()。remove();
    $(#+ buttonid +)。remove();
    });

    返回true;
    }

    函数imageClickHandler(imageuploadform){
    if(imageValidation(imageuploadform)){
    window.lastUploadImageIndex = $('。imageuploadform')。index(imageuploadform );
    return startImageUpload(imageuploadform);
    }
    返回false;
    }
    < / script>
    < / head>
    < body>
    < form id =QandAaction =insertQuestion.phpmethod =post>
    < table id =question>
    < tr>
    < th colspan =2>
    问题编号< span class =questionNum> 1< / span>
    < input type =hiddenclass =num_questionsname =numQuestionvalue =1>
    < / th>
    < / tr>
    < / table>

    < table id =questionBtnalign =center>
    < tr>
    < th>
    < input id =addQuestionBtnname =addQuestiontype =buttonvalue =Add QuestiononClick =insertQuestion(this.form)/>
    < / th>
    < / tr>
    < / table>

    < / div>< hr /><! - 此分隔关闭标签没有开放标签! - >

    < table id =qandatblalign =centercellpadding =0cellspacing =0border =0>
    < thead>
    < tr>
    < th width =5%class =qid>问题编号< / th>
    < th width =17%class =image>图片< / th>
    < / tr>
    < / thead>
    < / table>
    < div id =qandatbl_onthefly_container>
    < tbody>
    < / tbody>
    < / table>
    < / div>
    < div class =hiddenimg><! - 所有上传的图片文件ID都会在这里 - >< / div>
    < / form>
    < / body>

    通过执行以下var_dumps:

      var_dump($ question_ids); 
    var_dump($ imgresults);

    我得到以下结果:

      array(2){
    [1] => int(159)
    [2] => int(160)
    }
    array(2){
    [0] =>字符串(3)129
    [1] =>字符串(3)130
    }

    奇怪的是数字从0开始1为imgresult,我也不知道它为什么说明字符串,它应该是一个int。但是如果它来自一个输入,我可以调用bind_param i s ,就像在db中它的一个int?



    额外详情



    我没有收到这个mysqli ,我产生了一个类似mysqli的答案,奇怪的是,它正确地插入插入,即使它以0开头,就像上面插入的image_question一样:

      $ results = $ _POST ['value']; 
    foreach($ results as $ id => $ value)
    {
    $ answer = $ value;

    $ quesid = $ question_ids [$ id];

    foreach($ value as $ answer)
    {
    $ insertanswer-> bind_param(is,$ quesid,$ answer);

    $ insertanswer-> execute();

    if($ insertanswer-> errno){
    //在这里处理查询错误
    echo __LINE__。':'。$ insertanswer-> error;
    突破5;


    $ b $ / code $ / pre
    $ b $ var_dump($ result)显示与以前的1个问题的var转储:

      array(1){// var_dump($ question_ids); 
    [1] => int(171)
    } array(1){// var_dump($ imgresults);
    [0] =>字符串(3)130
    }数组(1){
    [1] => array(1){// var_dump($ results);
    [0] =>字符串(1)B}}


    解决方案

    使用Firebug我进入了HTML,经过很多挖掘(我的意思是很多挖掘),我知道你的问题是什么。但让我先说你的常识是对的,因为你了解自己需要编写的代码。



    无论如何,解决方案是你需要添加一个多维数组,并从0开始计数。你需要的是这样的:

      var imagecounter = 0; 

    var result ='';
    imagecounter ++;
    $ b ...


    '('。hiddenimg')。append('< input type =hiddenname =imgid ['+ imagecounter +'] []id ='+ imageID +'value ='+ imageID +'/>');

    现在您可以使用 gQuestion ++ 这证明了我的观点,你需要开始学习代码。如果您有几个小时的时间,请阅读您的代码并尝试了解正在发生的事情。它只能让你受益:)

    I want to insert data into Image_Question Table. but it does not perform an insert in the Image_Question Table.

    I am getting two errors:

    • Notice: Undefined offset: 0 in ... on line 305
    • Notice: Undefined offset: 3 in ... on line 305

    Here is the application you can use: Application

    To use app to see what is happening do the following:

    1. Click Add Question button twice to append two file inputs

    2. Now upload a file one at a time but do it like this. Upload a file in file input in row 1, then upload a file in row 2, then upload file in row 1 again then finally upload file in row 2.

    Below is mysqli code:

    // Prepare your statements ahead of time
    $questionsql = "INSERT INTO Question (QuestionNo) VALUES (?)";
    if (!$insert = $mysqli->prepare($questionsql)) {
      // Handle errors with prepare operation here
      echo __LINE__.': '.$mysqli->error;
    }
    
    $imagequestionsql = "INSERT INTO Image_Question (ImageId, QuestionId)  
    VALUES (?, ?)"; 
    
    if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) { 
      // Handle errors with prepare operation here 
     echo __LINE__.': '.$mysqli->error; 
    }
    
    //make sure both prepared statements succeeded before proceeding
    if( $insert && $insertimagequestion) {
      $c = count($_POST['numQuestion']);
      $question_ids = array();
    
      for($i = 0;  $i < $c; $i++ ) {
        $questionNo = $_POST['numQuestion'][$i];
    
        $insert->bind_param("i", $questionNo);
    
        $insert->execute();
    
        if ($insert->errno) {
            // Handle query error here
          echo __LINE__.': '.$insert->error;
          break 1;
        }
    
        $questionId = $mysqli->insert_id;
    
        $question_ids[$questionNo] = $questionId;
      }
    
      $imgresults = $_POST['imgid'];
      foreach($imgresults as $imgid => $imgvalue) { 
        $image = $imgvalue;
        $imgquesid = $question_ids[$imgid];  //LINE 305 where error is
    
        foreach($imgvalue as $image) {
          $insertimagequestion->bind_param("ii",$image, $imgquesid); 
          $insertimagequestion->execute();
    
          if ($insertimagequestion->errno) { 
            // Handle query error here
            echo __LINE__.': '.$insertimagequestion->error;
            break 2;
          }
        }
      }
      $insertimagequestion->close(); 
      $insert->close();
    }
    
    ?>
    

    Below is code which sets up the demo:

    function GetFormImageCount(){ 
      return $('.imageuploadform').length + 1;
    }
    
    var qnum = 1;
    var qremain = 5;
    
    function insertQuestion(form) {   
    
      if (qnum > 5)
        return;
    
      var $tbody = $('#qandatbl_onthefly > tbody');
      var $tr = $("<tr class='optionAndAnswer' align='center'>");
      var $qid = $("<td width='5%' class='qid'></td>").text(qnum);
      var $image = $("<td width='17%' class='image'></td>"); 
    
      $('.num_questions').each( function() {
    
        var $this = $(this);
    
        var $questionNumber = $("<input type='hidden' class='num_questionsRow'>").attr('name',$this.attr('name')+"[]").attr('value',$this.val());
    
        $qid.append($questionNumber);                             
    
        ++qnum;    
        $(".questionNum").text(qnum);
        $(".num_questions").val(qnum);
    
        --qremain;
        $(".questionRemain").text(qremain);
      });
    
      var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target_image' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" + 
        "<p class='imagef1_upload_form'><label>" + 
        "Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" + 
        "<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" + 
        "<p class='imagef1_upload_process'>Loading...<br/><img src='Images/loader.gif' /></p>" +
        "<input type='hidden' class='numimage' name='numimage' value='" + GetFormImageCount() + "' />" +
        "</p><p class='imagemsg'></p><p class='listImage'></p>" +
        "<iframe class='upload_target_image' name='upload_target_image' src='/' style='width:0px;height:0px;border:0px;solid;#fff;'></iframe></form>");   
    
      $image.append($fileImage);
    
      $tr.append($qid);
      $tr.append($image);  
      $tbody.append($tr);
    }
    
    function imageValidation(imageuploadform) {
      var val = $(imageuploadform).find(".fileImage").val();
      switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
        case 'gif':
        case 'jpg': 
        case 'jpeg':
        case 'pjpeg':
        case 'png':
          return true;
    
        case '':
          $(imageuploadform).find(".fileImage").val();
          alert("To upload an image, please select an Image File");
          return false;
    
        default:
          alert("To upload an image, please select an Image File");
          return false;
      }
      return false;
    }
    
    function htmlEncode(value) { return $('<div/>').text(value).html(); }
    
    function startImageUpload(imageuploadform){
      $(imageuploadform).find('.imagef1_upload_process').show()
      $(imageuploadform).find('.imagef1_upload_form').hide();
      $(imageuploadform).find('.imagemsg').hide();
      sourceImageForm = imageuploadform;
    
      return true;
    }
    
    var imagecounter = 0;
    
    function stopImageUpload(success, imageID, imagefilename) {
      var result = '';
      imagecounter++;
    
      if (success == 1){
        result = '<span class="imagemsg'+imagecounter+'">The file was uploaded successfully</span>';   
        $('.hiddenimg').eq(window.lastUploadImageIndex).append('<input type="text" name="imgid[]" id="'+imageID+'" value="' + imageID + '" />');
        $('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" data-imageID="'+imageID+'"  data-image_file_name="' + imagefilename + '" value="'+imageID+'">Remove</button><br/><hr/></div>');
      }
    
      $(sourceImageForm).find('.imagef1_upload_process').hide();
      $(sourceImageForm).find('.imagemsg').html(result);
      $(sourceImageForm).find('.imagemsg').show();
      $(sourceImageForm).find(".fileImage").replaceWith("<input type='file' class='fileImage' name='fileImage' />");
      $(sourceImageForm).find('.imagef1_upload_form').show();
    
    
      var _imagecounter = imagecounter;
    
      $('.listImage').eq(window.lastUploadImageIndex).find(".deletefileimage").on("click", function(event) {
        jQuery.ajax("deleteimage.php?imagefilename=" + $(this).attr('data-image_file_name')).done(function(data) {
          $(".imagemsg" + _imagecounter).html(data);
        });
    
        var buttonid = $(this).attr('value');
        $(this).parent().remove();
        $("#"+ buttonid  +"").remove();
      });
    
      return true;   
    }
    
    function imageClickHandler(imageuploadform){ 
      if(imageValidation(imageuploadform)){ 
        window.lastUploadImageIndex = $('.imageuploadform').index(imageuploadform); 
        return startImageUpload(imageuploadform); 
      }
      return false;
    }
    </script>
    </head>
    <body>
      <form id="QandA" action="insertQuestion.php" method="post">
        <table id="question">
          <tr>
            <th colspan="2">
              Question Number <span class="questionNum">1</span>
              <input type="hidden" class="num_questions" name="numQuestion" value="1">
            </th>
          </tr>
        </table>
    
        <table id="questionBtn" align="center">
          <tr>
            <th>
              <input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
            </th>
          </tr>
        </table>
    
      </div><hr/><!-- This Divide close tag has no open tag!-->
    
      <table id="qandatbl" align="center" cellpadding="0" cellspacing="0" border="0">
        <thead>
          <tr>
            <th width="5%" class="qid">Question Number</th>
            <th width="17%" class="image">Image</th>
          </tr>
        </thead>
      </table>
      <div id="qandatbl_onthefly_container">
        <table id="qandatbl_onthefly" align="center" cellpadding="0" cellspacing="0" border="0">
          <tbody>
          </tbody>
        </table>
      </div>
      <div class="hiddenimg"><!-- All uploaded image file ids go here --></div>
    </form>
    </body>
    

    By doing the following var_dumps:

       var_dump($question_ids);
        var_dump($imgresults);
    

    I get these results:

         array(2) { 
            [1]=> int(159)
            [2]=> int(160) 
            } 
    array(2) { 
    [0]=> string(3) "129"
    [1]=> string(3) "130" 
    }
    

    What is strange is the numbers start 0 then 1 for imgresult and also I do not know why it is stating string, it should be an int. But then if it is coming from an input do I call the bind_param i or s as in db its an int?

    EXTRA DETAILS:

    What I don't get is below this mysqli, I produce a similar mysqli for answers and what is strange is that it does the insert correctly even though it starts with 0 like the image_question insert above:

    $results = $_POST['value'];
    foreach($results as $id => $value) 
    {
        $answer = $value;
    
        $quesid = $question_ids[$id];   
    
        foreach($value as $answer) 
        {
            $insertanswer->bind_param("is", $quesid, $answer);
    
            $insertanswer->execute();
    
            if ($insertanswer->errno) {
                // Handle query error here
                echo __LINE__.': '.$insertanswer->error;
                break 5;
            }
        }
    }
    

    var_dump($result) shows with the previous var dumps for 1 question:

    array(1) { //var_dump($question_ids);
    [1]=> int(171) 
    } array(1) { //var_dump($imgresults);
    [0]=> string(3) "130" 
    } array(1) { 
    [1]=> array(1) { //var_dump($results);
    [0]=> string(1) "B" } } 
    

    解决方案

    Using Firebug I went onto the HTML and after a lot of digging (and I mean a lot of digging), I know what your issue is. But let me first say that Your Common Sense is right, for you to understand the code you need to write it yourself.

    Anyway the solution is you need to add a multi dimensional array and count through each row starting from 0. What you need is something like this:

     var imagecounter = 0;
    
          var result = '';
          imagecounter++;
    
    ....
    
    
         $('.hiddenimg').append('<input type="hidden" name="imgid[' + imagecounter + '][]" id="'+imageID+'" value="' + imageID + '" />');
    

    Now you did something like this earlier with gQuestion++ and this proves my point that you need to start learning the code. If you have a couple of hours spare just read your code and try to understand what is happening. It could only benefit you :)

    这篇关于它不会将数据插入到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆