It does not insert data into the database

I want to insert data into the Image_Question table. but it does not perform insertion in the Image_Question table.

I get two errors:

  • Note: Undefined offset: 0 in ... on line 305
  • Note: Undefined offset: 3 in ... at line 305

Here is the application you can use: Application

To use the application to see what is happening, do the following:

  • Double-click the Add Question button to add two input files.

  • Now upload the file one at a time, but do it like this. Download the file to the file on line 1, then load the file on line 2, then load the file on line 1, and then load the file on line 2.

The following is the 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 the code that installs 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 the following results:

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

It is strange that numbers start with 0, then 1 for imgresult, and also I don’t know why it indicates a string, it should be int. But if this comes from input, do I call bind_param i or s , as in db, is it int?

ADDITIONAL DETAILS:

What I do not get below this mysqli, I create a similar mysqli for the answers, and it is strange that it inserts correctly even if it starts at 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 previous dumps var 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" } } 
+6
source share
2 answers

Using Firebug, I went into HTML and after a lot of digging (and I mean a lot of digging), I know what the problem is. But let me first say that your good sense is correct so that you understand the code that you need to write yourself.

In any case, you need to add a multidimensional array and count each row starting at 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 have done something similar before with gQuestion++ , and this proves my point that you need to start learning the code. If you have a couple of hours, just read your code and try to understand what is going on. It may benefit you :)

+3
source

My answer will not be on a specific issue, but rather on a broader topic.

This is about how you do your work as a whole.
You have to change it.
Listen, all your questions are a way for big ones . And it gets even bigger. Still get fewer answers.
It makes you do desperate things - to deceive questions, generosity, bills - but all in vain. This road to nowhere.

You need to change the way you learn things and the way you use this wonderful site.
It is very important for everyone to know what tools they use. You must write the code yourself, asking for help only when you have a real solution.
As a result, you will understand your code. . It is important to understand what your code does. Each line. So, you can figure it out yourself and fix your code.
Otherwise, you are doomed to ask for help for each typo, as in this case.

Also, since you cannot get to the root of the problem, you need to send tons of codes along with your question, which makes the answer difficult.
There are three separate worlds in your question - JavaScript, PHP, and Mysql. And the problem belongs to only one of them. You must learn to separate your problems, at least to the extent of these areas.
Is it JS sending incorrect (unexpected) data from the client? Ok, remove all the PHP and Mysql code, leaving only JS. This will help both Stackoverflowers and even the problem itself.
Is this data okay? Are you sure? Print it out and make sure that this is exactly what you expect.
If everything is in order, go to the PHP part ( but remember to remove all JS from the question ).
Etc.

Ask your question not in general terms like β€œit does not insert”, but in the context of a specific data stream: β€œI expect that such data will go into the procedure, but I have another one.”
As soon as you start with this, you won’t need Stackoverflow to answer: you can trace the problem to the place where the data is unexpectedly erroneous. So you found the wrong place.

It is also very important to run the problem code. And run it in the environment itself, where you have your problem.
Running the code and checking the actual results is more efficient than looking at the code with your eyes.
Perhaps even some circumstances belong to your server and are unknown to other people, which makes them unable to answer your question at all.
In addition, people should not run PHP codes in their heads. It can work on several lines, but from some point it is simply impossible to completely run all the code and find the error.
That is why it is so important to run your code and print all the values, the results of functions, check the state of variables, etc. - and look for inconsistencies in them.

Of course, to use such a technique, you must understand which data is correct and which is not.
That's why it is so important to write your code from scratch and plan it yourself.
If it was you who decided what data should come from JS, you can tell whether it is good or bad. If it was someone else - you are at a dead end and doomed to ask again what is worse.
You need to break this vicious circle.
That is why it is so important to write code yourself, not to let someone else do it for you.

Hope this helps and good luck in learning.

+17
source

All Articles