• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 348
  • Last Modified:

It keeps displaying '0' for QuestionID in database if file is not uploaded first time

I am trying to pick out the correct question number from a table and inserting it in the database. Lets say I have a table where it appends rows and that I have 3 rows, the table below will look something like this:

  Question No     Image
    1                     (file input)
    2                    (file input)
    3                    (file input)

Below is the code that creates the table above:

var qnum = 1;  
var numimage = 0;

var $qid = $("<td class='qid'></td>").text(qnum);
var $image = $("<td class='image'></td>"); 

          $('.num_questions').each( function() {
	var $this = $(this);
     var $questionNumber = $("<input type='hidden' class='num_questionsRow'>").attr('name',$this.attr('name')+"[]")


    var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" + 
    "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>" + 
    "<input type='hidden' class='numimage' name='numimage' value='" + numimage + "' />" +
    "</p><p class='imagef1_cancel' align='center'><label>" +
    "<input type='reset' name='imageCancel' class='imageCancel' value='Cancel' /></label>" +
    "</p><p class='listImage' align='left'></p>" +		
    "<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");        



Open in new window

Now if I upload a file using one of the file inputs, then in the database it will insert the the name of the file and the question nmuber associated with it. So if I use this file input below:

    Question No     Image
    2                    (file input)

Image_Question Table:

ImageId   QuestionId
101                   2

The above table is correct and it does this if the file uplaods successfully first time.

The problem I am getting is if the file does not upload successfully for the first time or if I cancel the upload. Then what happens is that if I upload a file using the same file input in that row then when it comes to inserting the data, the 'QuestionId' will always display '0' for that particular file input, so it is like this:

ImageId   QuestionId
101                   0

The above table is obviously incorrect.

So my question is that why will it insert '0' for the QuestionId if in that file input a file was not successful or cancelled and then I upload a file in the second attempt (same or different file).

Below is the jquery code which controls the uplaoding of the files, (successful. unsuccessful or cancelled)

function stopImageUpload(success, imagefilename){
      var result = '';
      if (success == 1){
         result = '<span class="imagemsg'+imagecounter+'">The file was uploaded successfully</span><br/><br/>';      
         $('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>'); 
      else if (success == 2){
	      result = '<span class="imagemsg'+imagecounter+'"> The file upload was canceled</span><br/><br/>';
      else {
         result = '<span class="imagemsg'+imagecounter+'">There was an error during file upload</span><br/><br/>';

Open in new window

Below is the code where it inserts data into the database:

      "ImageFiles/" . $_FILES["fileImage"]["name"]);
      $result = 1;

 $lastID = $mysqli->insert_id;         
 $imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId)  
    VALUES (?, ?, ?)"; 
     if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) { 
      // Handle errors with prepare operation here 
       echo "Prepare statement err imagequestion"; 
$qnum = (int)$_POST['numimage'];

$insertimagequestion->bind_param("isi",$lastID, $sessid, $qnum); 

$sessid =  $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : ''); 
                if ($insertimagequestion->errno) { 
          // Handle query error here 

Open in new window

  • 4
  • 3
  • 2
2 Solutions
Ray PaseurCommented:
Please add these two lines to the top of all of your PHP scripts (and never write code without them).
ini_set('display_errors', TRUE);

Open in new window

With that you will be able to see if your script accidentally relied on an undefined variable.  Without it, PHP will silently convert undefined variables into null strings, or FALSE or zero values, depending on the context.  Search the PHP.NET web site for "type juggling" to see what you're fighting here.

I don't pretend to say that I've read that code or anything like that, but I've seen a lot of undefined variables in my life and unexpected zero values are one of the common symptoms.

Best of luck with debugging.  It will be a lot easier with the error visualization, I promise! ~Ray
carlbrooks1995Author Commented:

I am not reciveing any php errors, I did have the error report on when I wrote this code but if a file has not been uploaded successfully, or it has been cancelled or if it has been uploaded successfully, I get no errors displayed at all. No undefined index or anything. I am not sure that the problm is caused by php, it be caused by the jquery but I am not sure. It could be caused by the iframe. I forgot to put below the insert php code that in does include a javascript code which controls the iframe and that is below:

  <script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result ? 'true' : 'false'; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');</script>

Open in new window

Chris StanyonCommented:
I haven't gone through your code in detail but I do have a few observations that may or may not help you fix your problem.

Firstly you say that you are not receiving any PHP errors, but the errors will be output inside your iFrame, which you currently have set to zero width and zero height, so effectively you're hiding them. Change that for testing.

If you add more than 1 question, you will end up with more than 1 iframe with the same name. When you click the upload button you are submitting your form to one of these iframes - no way of telling which, but probably the last one created. Again, for testing set a height and width to your iFrame so you can see exactly what's happening. It's probably advisable to move the IFrame out of your loop, so you only ever have one.

Your database insert function looks like it will always call the stopImageUpload() function with success, because you explicitly set it to that in the code - $result = 1;

You haven't said how you 'cancel' an upload so can't really help you there.

Finally, having been involved in your previous question, I see you are still using your old, original code for adding questions to the table. Bearing in mind what we've already discussed, it more than probable that your variables are being set, re-set or generally being misused.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

carlbrooks1995Author Commented:
@ChrisStanyon Ok thanks to what you said about extending the iframes  we are able to see an php notice occur. If I file is uploaded successfully first time then there is no notice the appears at all in the iframe. But if the file was unsuccessful or cancelled then there is still no errors until I upload another file which will become successul, then it displays a notice for that file stating:

Notice: Undefined index: numvideo in /web/stud/...../app/imageupload.php on line 150

This is pointing to this line of code in the php where it inserts the data in the db:

$qnum = (int)$_POST['numimage'];

Open in new window

What do I need to include inorder to get this to work as that because this is getting undefined, qnum will not post the number of the question number but will instead insert number '0' as it is undefined
Chris StanyonCommented:
Hi Carl,

Firstly the error points to a variable called 'numvideo' not being defined, but the line you point to is looking for a POST variable called numimage - nowhere in your code is there even a mention of a variable called numvideo

I've already pointed out that your jQuery code above is a bit of a mess. Logically, it just doesn't make sense, so I'm not surprised that you're hitting undefined variables. In a previous question of yours, I gave you the code to clean it up and make it more logical. I'm not going to go over the same issues again - you need to re-read my comments from your last question.

The code you've posted above is only part of your code - it's not a complete listing, which makes it difficult to see the big picture. How do you fire the jQuery code, how do you 'cancel' a file upload, how is your html structured etc.

If you have a live link to this (a demo or staging server) then I can take a look and maybe point you in the right direction, but if you keep heading forward with your code as it is, you will just run into more problems later on.
carlbrooks1995Author Commented:
@ChrisStanyon Yeah sorry, I actually have 3 file upload scripts, one for video, one for images and one for audio, they are all similar code except they have different variables such as numimage, numvideo and num audio. But it is numimage not numvideo I was suppose to be referring to

The reason I have not try to clean the code with what yuo have stated is because the code works fine in the jquery and I don't have that much time left so I want to leave the juqery code as it is, plaus the whole code is 10 times bigger then what I have posted so don't really want to mess everything up and confuse myself.

The problem I have is just the inserting part of the data (the php code where it inserts data into db), that is the only problem I am getting but like I said I am recieving undefined variables.

Btw the juqery for how the cancel button works is below:

function startImageUpload(imageuploadform){

        $(imageuploadform).find(".imageCancel").on("click", function(event) {
			  $("iframe[name='upload_target']").attr("src", "javascript:'<html></html>'");
    return stopImageUpload(2);

      return true;

Open in new window

Just need your help on why it is rturning undefined variable for numimage for next file successfully uploaded after a cancellation or an unsuccessful file upload previously
Chris StanyonCommented:
Without cleaning up your code, I can't really help any more. As I've said a few times, your code doesn't really make sense - there's no real logic behind it. If it works as it is, it's down to luck more than judgement, and debugging is going to be very difficult.

As for not cleaning up code because of time constraints, that seems a little counter-intuitive. You'll likely to spend much longer hacking and debugging your exisiting code. You've already spent a couple of days just trying to track a simple variable! Something that could be done in 2 minutes with the right code.

You've just introduced yet another javascript function that doesn't really have a logical structure (startImageUpload). The onclick event ought to be called in document.ready. The code doesn't look like it cancels an upload - just resets the content of the iFrame, and you look like you're trying to return the return value of your stopImageUpload() function - a function that doesn't return anything! Also, you haven't shown anywhere in any of your code where this function fits in.

If you insist on sticking with your own code, then there's not much more I can do. Sorry.
Ray PaseurCommented:
@carlbrooks1995: From the dialog here, I recommend that you step back from trying to write PHP code and take some time to get some structured learning about how to use PHP and MySQL(i).  I recommend that you buy this book and give yourself a month or so to work through the chapters, following the examples to see how this stuff all works.  You may be able to learn some parts of PHP by hacking about with trial and error, but if you succeed in that approach, you will be in the minority and you will lack the foundation that most programmers consider essential to success.

Going forward, you will also benefit from a structured approach to programming.  First, develop the server-side logic.  Make sure that the plain and simple HTML forms and the server side action scripts interact in sensible ways.  Remove the unnecessary variables from your code, and apply consistent naming conventions and coding standards (make a Google search for "Zend coding standards" and start with that pattern).  Use data visualization techniques like var_dump() as often as possible to ensure that your program code is doing something sensible with the inputs and the intermediate variables before producing the outputs.

After you can demonstrate that the server-side logic works correctly with plain HTML inputs, then consider building up the client-side layer with JavaScript or a jQuery library.  But don't even start with that side of the project until you are 100% certain of the server side.  Once you start using the AJAX and related libraries you cannot readily see what the server is doing, and so you really need to be able to depend on the server side of the programming at that point.

Good luck with it (and buy that book), ~Ray
carlbrooks1995Author Commented:
Your both right, I need to start learning how to do php and mysqli properly before being able to build an application. Problem is that this a project I am doing in uni but I have no choice but to use php, ajax, jquery etc even though I have only done php for 1 semester and never used jquery or ajax in my life before this year.

Thanks both of you for your efforts, I will buy that book and hopefully if I can sort this problem out, after this project I will definetly start learning php and mysqli from scratch and go through the examples so I know what needs to be done and be a better programmer.

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now