PHP Multiple File Upload

I've been working on a mobile building inspection form. The form is dynamic and the user is allowed to "toggle" on/off which inspection items to save to the database from a list.  When the user hits submit, we read through an array and insert records accordingly.  This all works.

I'm now trying to allow the user to insert a picture for each record.  Then, insert the picture unique name into the database and save the file to the server.  I could get this to work for one record at a time, but based on the users design request, we need to allow them to upload multilple images.

This code works to insert the records to the database if the "toggle' is "on".  However, I'm not getting a value to be passed into the filename variable and the file is not uploading to the server.  I've looked this over for several days.

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
 
  mysql_select_db($database_FCAInspection, $FCAInspection);
//loop through the input values

for ($i=0, $len=count($_POST['deficiencyidtext']); $i < $len; $i++) {
$varFlipSwitch = $_POST['flipswitch1'][$i];
if($varFlipSwitch == "on"){
//save file to folder and change filename to insert into sql statement


$uploads_dir = 'images';
foreach ($_FILES["file"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["file"]["tmp_name"][$key];
        $name = $_FILES["file"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }

} 
$insertSQL = sprintf("INSERT INTO inspectiondetails (DeficiencyId, PriorityId, `Description`,Image) VALUES (%s, %s, %s, '$name')",
                    GetSQLValueString($_POST['deficiencyidtext'][$i], "int"),
   	        		GetSQLValueString($_POST['prioritymenu1'][$i], "int"),
                    GetSQLValueString($_POST['descriptiontextinput1'][$i], "text"));
$Result1 = mysql_query($insertSQL, $FCAInspection) or die(mysql_error());
}

}//end loop
  $insertGoTo = "Home.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

Open in new window

I need a new set of eyes on this code.  Thanks in advance
FSAAdminAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
I can show you how to upload multiple files.

<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/reserved.variables.files.php
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/function.getimagesize.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('uploads' DIRECTORY)
$uploads = 'RAY_junk';
if (!is_dir($uploads))
{
    mkdir($uploads);
}

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME URL
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

0
FSAAdminAuthor Commented:
that's really good example.  

IMy problem is that I'm not bringing back the value of the file name after the user selects it.  I'm writing a null into the database and the file is not being uploaded.

my input statement is:
                    <input type="file" name="file[]" id="file[]" />

Open in new window


my form action is:
><form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="form1" id="form1">

Open in new window


then I'm trying to use the code above
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) 

Open in new window


I'd like to try to fix all the issues with the code I have started.
0
Ray PaseurCommented:
I think we would need to see the HTML form.  It may need some tweaks.

You may also benefit from using var_dump() to print out the contents of the $_POST and $_FILES arrays.  Then once you can see the data, it may be easier to write the programming to copy and store the data where you want it.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

FSAAdminAuthor Commented:
Here's the HTML - appreciate you taking time to look at this.


<link href="jquery-mobile/jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css" />
<link href="jquery-mobile/jquery.mobile.structure-1.0.min.css" rel="stylesheet" type="text/css" />
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>

</head>

<body>
<div data-role="page" id="IDS4">
  <div data-role="header">
    <h1>Header<a href="Home.php" data-role="button" data-icon="home">Home</a></h1>
  </div>
  <div data-role="content"><form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="form1" id="form1">
    <table id="table1">
      <tr>
        <td width="74">idDeficiency</td>
        <td width="152">Deficiency</td>
        <td width="302">Description</td>
        <td width="137">Ratings</td>
        <td width="221">Toggle</td>
        <td width="200">Image</td>
      </tr>
      <?php do { ?>
        <tr>
          <td><div data-role="fieldcontain">
			<input name="deficiencyidtext[]" type="text" id="deficiencyidtext[]" value=<?php echo $row_Recordset1['idDeficiency']; ?> size="3" readonly="readonly"/>
			</div>
</td>
          <td><div data-role="fieldcontain">
            <label for="deficiencytext"></label>
              <?php echo $row_Recordset1['Deficiency']; ?></div></td>
          <td><div data-role="fieldcontain">
              <label for="descriptiontextinput1[]"></label>
              <textarea name="descriptiontextinput1[]" id="descriptiontextinput1[]"></textarea>
            </div>
          <td>      <div class="ui-block-d"><div data-role="fieldcontain">
            <label for="prioritymenu1[]" class="select"></label>
            <select name="prioritymenu1[]" size="1" id="prioritymenu1[]" onchange="valueselect(this.value)" >
              <?php
do {  
?>
              <option value="<?php echo $row_Priority['idPriority']?>"><?php echo $row_Priority['Priority']." - ".$row_Priority['Description']?></option>
              <?php
} while ($row_Priority = mysql_fetch_assoc($Priority));
  $rows = mysql_num_rows($Priority);
  if($rows > 0) {
      mysql_data_seek($Priority, 0);
	  $row_Priority = mysql_fetch_assoc($Priority);
  }
?>
            </select>
        </div></td>

          <td>
            <div data-role="fieldcontain">
            <label for="flipswitch1[]"></label>
            <select name="flipswitch1[]" id="flipswitch1[]" onchange="valueselect2(this.value)" data-role="slider" data-theme="e">
              <option value="off" selected="selected">Off</option>
              <option value="on">On</option>
            </select>
            <input name="testVal[]" type="hidden" id="testVal[]" />
            </div></td>
                    <td><label for="image"></label>
                    <input type="file" name="file[]" id="file[]" /></td>
        </tr>

        <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>

    </table>
<script language="javascript">

	function valueselect(myval)
	{
//		alert(myval)
	}
	</script>
<script language="javascript">

	function valueselect2(myval2)
	{
//	alert(myval2)
	}
	</script>
    
     <input name="SubmitDef" type="submit" id="SubmitDef" value="Submit" onclick="return confirm('Are you sure you want upload?');" />
  <input type="hidden" name="MM_insert" value="form1" />
  </form></div>
  <div data-role="footer">
    <h4>Footer</h4>
  </div>
</div>
</body>
</html>

Open in new window

0
FSAAdminAuthor Commented:
I added a script that moves the value from the file field to a hidden field and look for

GetSQLValueString($_POST['testVal'][$i],"text")

Open in new window

and the file name gets inserted into the database.  I understand this isn't the method to go with, I just thought it was interesting that I could read the value from the hidden field but not from the $_FILES array as it was intended.  I'm definitely missing something.
0
FSAAdminAuthor Commented:
Still having problems moving the file the file to the destination location
0
Ray PaseurCommented:
Have you got this on a test version of the web site with a public-facing URL?  I would like to see the HTML form.  It's hard to envision what is in the HTML by looking that the PHP, because I don't have access to the data that the PHP script uses to generate the HTML.

You can use var_dump($_FILES) to see what the $_FILES array contains.
0
FSAAdminAuthor Commented:
0
Ray PaseurCommented:
Let's try this... Change the action script to use a new target.  Currently it's making a POST-method request to itself (I think).

<form action="/FCAInspection/ExchangeHelp.php?opsSysId=5" ...

The new target script will be for data visualization only.

<?php
error_reporting(E_ALL);
echo '<pre>';
var_dump($_POST);
var_dump($_FILES);

Open in new window

Armed with that we will be able to see what is coming through in the HTTP request as the form is posted.
0
FSAAdminAuthor Commented:
Ok, I've done that and as you can see, there is nothing being passed to the variable 'file[]'.  The "testVal[]" is a hidden field that I'm using to pass the filename to since I couldn't get the filename through the array.

array(7) {
  ["deficiencyidtext"]=>
  array(4) {
    [0]=>
    string(2) "37"
    [1]=>
    string(2) "38"
    [2]=>
    string(3) "160"
    [3]=>
    string(3) "173"
  }
  ["descriptiontextinput1"]=>
  array(4) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
  }
  ["prioritymenu1"]=>
  array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "1"
    [2]=>
    string(1) "1"
    [3]=>
    string(1) "1"
  }
  ["flipswitch1"]=>
  array(4) {
    [0]=>
    string(2) "on"
    [1]=>
    string(3) "off"
    [2]=>
    string(3) "off"
    [3]=>
    string(3) "off"
  }
  ["testVal"]=>
  array(4) {
    [0]=>
    string(7) "187.jpg"
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
  }
  ["SubmitDef"]=>
  string(6) "Submit"
  ["MM_insert"]=>
  string(5) "form1"
}
array(0) {
}
0
Ray PaseurCommented:
Yes, I see.  It looks like the JavaScript that is trying to operate on the input type="file" is not working, and that actually makes a lot of sense from a security perspective.  Think about it for a moment... If JavaScript could manipulate the contents of the file input control, it could steal files from the client computer without any notice or permission from the client human.  That dog won't hunt!

You might try removing the JavaScript onChange from this statement:

<input name="file[]" type="file" id="file[]" onchange="valueselect3(this.value)" />

And just make it say this:

<input name="file[]" type="file" id="file[]" />
0
FSAAdminAuthor Commented:
For clarification, the reason I added the javascript on-change  was to be sure that I was passing the name of the file in.   This is the only way I was able to capture the file name and insert into by SQL statement.

Now that I've removed the javascript from the on-change event, I still do not get any value's in the $_FILES array.

array(7) {
  ["deficiencyidtext"]=>
  array(4) {
    [0]=>
    string(2) "37"
    [1]=>
    string(2) "38"
    [2]=>
    string(3) "160"
    [3]=>
    string(3) "173"
  }
  ["descriptiontextinput1"]=>
  array(4) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
  }
  ["prioritymenu1"]=>
  array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "1"
    [2]=>
    string(1) "1"
    [3]=>
    string(1) "1"
  }
  ["flipswitch1"]=>
  array(4) {
    [0]=>
    string(2) "on"
    [1]=>
    string(3) "off"
    [2]=>
    string(3) "off"
    [3]=>
    string(3) "off"
  }
  ["testVal"]=>
  array(4) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
  }
  ["SubmitDef"]=>
  string(6) "Submit"
  ["MM_insert"]=>
  string(5) "form1"
}
array(0) {
}
0
Ray PaseurCommented:
I installed this script on my server here.  It found the $_FILES array with no problems.
http://www.laprbass.com/RAY_temp_fsaadmin.php

Here is the "bounce request" script that it posted to:

<?php // RAY_bounce_request.php
error_reporting(E_ALL);
// die('DISABLED ON THIS SERVER');
echo "<pre>" . PHP_EOL;
echo "HERE IS THE POST ARRAY:" . PHP_EOL;
var_dump($_POST);

echo "HERE IS THE FILES ARRAY:" . PHP_EOL;
var_dump($_FILES);

Open in new window

And here is the script that I ran.

<?php // RAY_temp_fsaadmin.php
error_reporting(E_ALL);
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MODIFIED Document</title>
<link href="jquery-mobile/jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css" />
<link href="jquery-mobile/jquery.mobile.structure-1.0.min.css" rel="stylesheet" type="text/css" />
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>

</head>

<body>
<div data-role="page" id="IDS4">
  <div data-role="header">
    <h1>Header<a href="Home.php" data-role="button" data-icon="home">Home</a></h1>
  </div>
  <div data-role="content"><form action="RAY_bounce_request.php" method="POST" enctype="multipart/form-data" name="form1" id="form1">
    <table id="table1">
      <tr>
        <td width="74">idDeficiency</td>
        <td width="152">Deficiency222</td>
        <td width="302">Description</td>
        <td width="137">Ratings</td>
        <td width="221">Toggle</td>
        <td width="200">Image</td>
      </tr>
              <tr>
          <td><div data-role="fieldcontain">
			<input name="deficiencyidtext[]" type="text" id="deficiencyidtext[]" value=37 size="3" readonly="readonly"/>
			</div>
</td>
          <td><div data-role="fieldcontain">
            <label for="deficiencytext"></label>
              Exposed Structural Systems (Unpainted, Painted, Spray-On, Decorative)</div></td>
          <td><div data-role="fieldcontain">
              <label for="descriptiontextinput1[]"></label>
              <textarea name="descriptiontextinput1[]" id="descriptiontextinput1[]"></textarea>
            </div>
          <td>      <div class="ui-block-d"><div data-role="fieldcontain">
            <label for="prioritymenu1[]" class="select"></label>
            <select name="prioritymenu1[]" size="1" id="prioritymenu1[]" onchange="valueselect(this.value)" >
                            <option value="1">1 - IMMEDIATE</option>
                            <option value="2">2 - WITHIN YEAR ONE</option>
                            <option value="3">3 - WITHIN YEARS TWO TO FIVE</option>
                            <option value="4">4 - WITHIN YEARS SIX TO TEN</option>
                            <option value="5">5 - OVER TEN YEARS</option>
                          </select>
        </div></td>

          <td>
            <div data-role="fieldcontain">
            <label for="flipswitch1[]"></label>
            <select name="flipswitch1[]" id="flipswitch1[]" onchange="valueselect2(this.value)" data-role="slider" data-theme="e">
              <option value="off" selected="selected">Off</option>
              <option value="on">On</option>
            </select>
            </div></td>
                    <td><label for="image"></label>
                    <input name="file[]" type="file" id="file[]"/>
                    <input name="testVal[]" type="hidden" id="testVal[]" />
                    </td>
        </tr>

                <tr>
          <td><div data-role="fieldcontain">
			<input name="deficiencyidtext[]" type="text" id="deficiencyidtext[]" value=38 size="3" readonly="readonly"/>
			</div>
</td>
          <td><div data-role="fieldcontain">
            <label for="deficiencytext"></label>
              Directly Applied Systems</div></td>
          <td><div data-role="fieldcontain">
              <label for="descriptiontextinput1[]"></label>
              <textarea name="descriptiontextinput1[]" id="descriptiontextinput1[]"></textarea>
            </div>
          <td>      <div class="ui-block-d"><div data-role="fieldcontain">
            <label for="prioritymenu1[]" class="select"></label>
            <select name="prioritymenu1[]" size="1" id="prioritymenu1[]" onchange="valueselect(this.value)" >
                            <option value="1">1 - IMMEDIATE</option>
                            <option value="2">2 - WITHIN YEAR ONE</option>
                            <option value="3">3 - WITHIN YEARS TWO TO FIVE</option>
                            <option value="4">4 - WITHIN YEARS SIX TO TEN</option>
                            <option value="5">5 - OVER TEN YEARS</option>
                          </select>
        </div></td>

          <td>
            <div data-role="fieldcontain">
            <label for="flipswitch1[]"></label>
            <select name="flipswitch1[]" id="flipswitch1[]" onchange="valueselect2(this.value)" data-role="slider" data-theme="e">
              <option value="off" selected="selected">Off</option>
              <option value="on">On</option>
            </select>
            </div></td>
                    <td><label for="image"></label>
                    <input name="file[]" type="file" id="file[]"/>
                    <input name="testVal[]" type="hidden" id="testVal[]" />
                    </td>
        </tr>

                <tr>
          <td><div data-role="fieldcontain">
			<input name="deficiencyidtext[]" type="text" id="deficiencyidtext[]" value=160 size="3" readonly="readonly"/>
			</div>
</td>
          <td><div data-role="fieldcontain">
            <label for="deficiencytext"></label>
              Other</div></td>
          <td><div data-role="fieldcontain">
              <label for="descriptiontextinput1[]"></label>
              <textarea name="descriptiontextinput1[]" id="descriptiontextinput1[]"></textarea>
            </div>
          <td>      <div class="ui-block-d"><div data-role="fieldcontain">
            <label for="prioritymenu1[]" class="select"></label>
            <select name="prioritymenu1[]" size="1" id="prioritymenu1[]" onchange="valueselect(this.value)" >
                            <option value="1">1 - IMMEDIATE</option>
                            <option value="2">2 - WITHIN YEAR ONE</option>
                            <option value="3">3 - WITHIN YEARS TWO TO FIVE</option>
                            <option value="4">4 - WITHIN YEARS SIX TO TEN</option>
                            <option value="5">5 - OVER TEN YEARS</option>
                          </select>
        </div></td>

          <td>
            <div data-role="fieldcontain">
            <label for="flipswitch1[]"></label>
            <select name="flipswitch1[]" id="flipswitch1[]" onchange="valueselect2(this.value)" data-role="slider" data-theme="e">
              <option value="off" selected="selected">Off</option>
              <option value="on">On</option>
            </select>
            </div></td>
                    <td><label for="image"></label>
                    <input name="file[]" type="file" id="file[]"/>
                    <input name="testVal[]" type="hidden" id="testVal[]" />
                    </td>
        </tr>

                <tr>
          <td><div data-role="fieldcontain">
			<input name="deficiencyidtext[]" type="text" id="deficiencyidtext[]" value=173 size="3" readonly="readonly"/>
			</div>
</td>
          <td><div data-role="fieldcontain">
            <label for="deficiencytext"></label>
              Suspended Systems</div></td>
          <td><div data-role="fieldcontain">
              <label for="descriptiontextinput1[]"></label>
              <textarea name="descriptiontextinput1[]" id="descriptiontextinput1[]"></textarea>
            </div>
          <td>      <div class="ui-block-d"><div data-role="fieldcontain">
            <label for="prioritymenu1[]" class="select"></label>
            <select name="prioritymenu1[]" size="1" id="prioritymenu1[]" onchange="valueselect(this.value)" >
                            <option value="1">1 - IMMEDIATE</option>
                            <option value="2">2 - WITHIN YEAR ONE</option>
                            <option value="3">3 - WITHIN YEARS TWO TO FIVE</option>
                            <option value="4">4 - WITHIN YEARS SIX TO TEN</option>
                            <option value="5">5 - OVER TEN YEARS</option>
                          </select>
        </div></td>

          <td>
            <div data-role="fieldcontain">
            <label for="flipswitch1[]"></label>
            <select name="flipswitch1[]" id="flipswitch1[]" onchange="valueselect2(this.value)" data-role="slider" data-theme="e">
              <option value="off" selected="selected">Off</option>
              <option value="on">On</option>
            </select>
            </div></td>
                    <td><label for="image"></label>
                    <input name="file[]" type="file" id="file[]"/>
                    <input name="testVal[]" type="hidden" id="testVal[]" />
                    </td>
        </tr>

            </table>
<script language="javascript">

	function valueselect(myval)
	{
//		alert(myval)
	}
	</script>
<script language="javascript">

	function valueselect2(myval2)
	{
//	alert(myval2)
	}
	</script>

     		<script type="text/javascript">
		function valueselect3(myval3)
		{
			var fullPath=document.getElementById('file[]').value;
			if (fullPath){
				var startIndex = (fullPath.indexOf('\\')>=0?fullPath.lastIndexOf('\\'):fullPath.lastIndexOf('/'));
				var filename = fullPath.substring(startIndex);
				if (filename.indexOf('\\')===0||filename.indexOf('/')===0)
				{
					filename=filename.substring(1);

				}
			}

			document.getElementById('testVal[]').value = filename
		}
        </script>


     <input name="SubmitDef" type="submit" id="SubmitDef" value="Submit" onclick="return confirm('Are you sure you want upload?');" />
  <input type="hidden" name="MM_insert" value="form1" />
  </form></div>
  <div data-role="footer">
    <h4>Footer</h4>
  </div>
</div>
</body>
</html>

Open in new window

Here is the output from running that script.

HERE IS THE POST ARRAY:
array(7) {
  ["deficiencyidtext"]=>
  array(4) {
    [0]=>
    string(2) "37"
    [1]=>
    string(2) "38"
    [2]=>
    string(3) "160"
    [3]=>
    string(3) "173"
  }
  ["descriptiontextinput1"]=>
  array(4) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
  }
  ["prioritymenu1"]=>
  array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "1"
    [2]=>
    string(1) "1"
    [3]=>
    string(1) "1"
  }
  ["flipswitch1"]=>
  array(4) {
    [0]=>
    string(3) "off"
    [1]=>
    string(3) "off"
    [2]=>
    string(3) "off"
    [3]=>
    string(3) "off"
  }
  ["testVal"]=>
  array(4) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
  }
  ["SubmitDef"]=>
  string(6) "Submit"
  ["MM_insert"]=>
  string(5) "form1"
}
HERE IS THE FILES ARRAY:
array(1) {
  ["file"]=>
  array(5) {
    ["name"]=>
    array(4) {
      [0]=>
      string(0) ""
      [1]=>
      string(23) "83_gray_frugal_mule.png"
      [2]=>
      string(0) ""
      [3]=>
      string(10) "3stars.png"
    }
    ["type"]=>
    array(4) {
      [0]=>
      string(0) ""
      [1]=>
      string(9) "image/png"
      [2]=>
      string(0) ""
      [3]=>
      string(9) "image/png"
    }
    ["tmp_name"]=>
    array(4) {
      [0]=>
      string(0) ""
      [1]=>
      string(14) "/tmp/phpnXOAEk"
      [2]=>
      string(0) ""
      [3]=>
      string(14) "/tmp/phppdbhfe"
    }
    ["error"]=>
    array(4) {
      [0]=>
      int(4)
      [1]=>
      int(0)
      [2]=>
      int(4)
      [3]=>
      int(0)
    }
    ["size"]=>
    array(4) {
      [0]=>
      int(0)
      [1]=>
      int(8840)
      [2]=>
      int(0)
      [3]=>
      int(1195)
    }
  }
}

Open in new window

0
FSAAdminAuthor Commented:
I've taken your scripts as they are still don't get the file array information

http://bfwebdev.nmsu.edu/FCAInspection/RAY_temp_fsaadmin.php

HERE IS THE POST ARRAY:
array(6) {
  ["deficiencyidtext"]=>
  array(4) {
    [0]=>
    string(2) "37"
    [1]=>
    string(2) "38"
    [2]=>
    string(3) "160"
    [3]=>
    string(3) "173"
  }
  ["descriptiontextinput1"]=>
  array(4) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
  }
  ["prioritymenu1"]=>
  array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "1"
    [2]=>
    string(1) "1"
    [3]=>
    string(1) "1"
  }
  ["flipswitch1"]=>
  array(4) {
    [0]=>
    string(2) "on"
    [1]=>
    string(3) "off"
    [2]=>
    string(3) "off"
    [3]=>
    string(3) "off"
  }
  ["testVal"]=>
  array(4) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
  }
  ["MM_insert"]=>
  string(5) "form1"
}
HERE IS THE FILES ARRAY:
array(0) {
}

Open in new window

0
Ray PaseurCommented:
Well, maybe it is time to start over from a simple foundation and gradually build up to a working script.  This process is often faster than trying to isolate what went wrong via trial and error.  However if you want to post the action script that could only find the empty $_FILES array, I will be glad to take a look at it.  The array should be present unless there is something in the JavaScript that is tinkering with it.  It's present when I test the script I posted above, whether or not I choose any files for upload.  So you might want to give it a try without the JQuery links.
0
FSAAdminAuthor Commented:
I've removed the JavaScript from the on-change events.   I found that this piece of code is necessary to disable AJAX so that Jquery and PHP play well together.  After adding this code I was able to see the file information into the $_FILES array.  
<script>
 $(document).ready(function() {
  // disable ajax nav
  $.mobile.ajaxEnabled = false;
 });
</script>

Open in new window


Now I'm back to getting the script to save the filename and uploading the file to the server.  This script will get the value "array" added to the database, but not the actual filename.  Also, it is failing to move_uploaded_file

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

function uploadImage(){
   		$allowedExts = array("jpg", "jpeg", "gif", "png", "JPG", "JPEG","GIF", "PNG");
	   	$extension = end(explode(".", $_FILES["file"]["name"]));

		
		if ((($_FILES["file"]["type"] == "image/gif")
			|| ($_FILES["file"]["type"] == "image/jpeg")
			|| ($_FILES["file"]["type"] == "image/JPG")
			|| ($_FILES["file"]["type"] == "image/JPEG")
			|| ($_FILES["file"]["type"] == "image/GIF")
			|| ($_FILES["file"]["type"] == "image/PNG")
			|| ($_FILES["file"]["type"] == "image/png")
			|| ($_FILES["file"]["type"] == "image/pjpeg"))
			&& in_array($extension, $allowedExts))	   	{
			move_uploaded_file($_FILES["file"]["tmp_name"],
	      				"images/" . $_FILES["file"]["name"]);

	  	}
	  	return $_FILES["file"]["name"];
 	}
	

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
 
  mysql_select_db($database_FCAInspection, $FCAInspection);
//loop through the input values

for ($i=0, $len=count($_POST['deficiencyidtext']); $i < $len; $i++) {
$filename=uploadImage();
$varFlipSwitch = $_POST['flipswitch1'][$i];
if($varFlipSwitch == "on"){

$insertSQL = sprintf("INSERT INTO inspectiondetails (DeficiencyId, PriorityId, `Description`,Image) VALUES (%s, %s, %s, '$filename')",
                    GetSQLValueString($_POST['deficiencyidtext'][$i], "int"),
   	        		GetSQLValueString($_POST['prioritymenu1'][$i], "int"),
                    GetSQLValueString($_POST['descriptiontextinput1'][$i], "text"));

$Result1 = mysql_query($insertSQL, $FCAInspection) or die(mysql_error());
}

}//end loop

Open in new window

0
Ray PaseurCommented:
...it is failing to move_uploaded_file
Please refer back to the original post that shows how to upload files.

All of the PHP functions are documented in the PHP.net man pages.  If you go there, you will see how to use move_uploaded_file() and you will see what return values can be produced by the function.  If your script does not test the return values, you're missing an essential part of the programming!

I don't know how you know it is failing, since the script does not test the return value.  Maybe check the permissions on the target directory to make sure you can write into it?

If you're new to PHP and you happen to be trying to learn it by copying DreamWeaver code, please let me gently point you in a better direction.  Dreamweaver creates some of the worst PHP code ever, and you would be better off with almost any other basis for your knowledge of PHP.  This article can lead you to some good learning tools.  
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

If you don't already own it, the Welling/Thompson book is particularly good.
0
FSAAdminAuthor Commented:
Yes, I'm a novice with PHP, however, I was able to get the script above to work with a single file upload.  I'm trying to get it with the mutliple files.  I will continue to explore.  Still seeking assistaince
0
Ray PaseurCommented:
You may want to look closely at the structure of $_FILES.  It's not at all intuitive!  Make a simple one-file upload and use var_dump($FILES) to see what the request presents to the action script.  Then make a three-file upload and compare the contents of var_dump($_FILES).  Try this a couple of different ways, omitting one or more of the file selections.  I think you will find that you need to think about one-file and multi-file uploads in slightly different terms!
0
FSAAdminAuthor Commented:
I'm planning to dedicate more time to this problem this week.   I do believe that I have not been clear on what trying to do.  I do want upload a single imagmage when inserting a record into a database.  This will be dynamic based on values the user selects to get to the page to select an image/file to upload and they may have a several records to insert into the database with a 1:1 relationship to a file/image to upload.  

I will be starting new.
0
FSAAdminAuthor Commented:
I am back at this little project.  I'm able to get all my parameters passed into my form for submission.  However, if I attempt to submit the page, the file doesn't upload nor does the file name get saved.  If I refresh the screen before selecting my file, I can pull in the file information and upload it.

I'm just a JQUERY Mobile novice but it seems that there should be a setting or script that would allow me to accomplish this.

I've currently resorted to use PureUpload php and get the same results.

If I got the page directly to enter the values, the Pure Upload PHP work perfect.  But if I try to pass paramaters to the page and submit the form, it fails to capture the file.
0
Ray PaseurCommented:
There might be a security issue in your design.  You cannot under any circumstances prepopulate the contents of $_FILES (same as <input type="file">) because it would allow a server to attack a client machine and steal data.  So if you're trying to add value data to an input control of type="file" you would need to redesign the application.
0
FSAAdminAuthor Commented:
Spent some time last night looking at this and I'm now able to upload the file correctly and it seems that my sql for inserting the form details is correct but it doesn't.  

Here's the code for inserting the filename and other form elements into the database.  I'm omitting the connection account information but it's at the top of the form and works as that connection is consistent on my other pages and works.

<?php $filename = "";
$status = 0;
session_start();
$_SESSION['property'] = $_POST['propertyTxt'];
$_SESSION['deficiency'] = $_POST['deficiencyTxt'];
$_SESSION['details'] = $_POST['descriptionTxt'];
$_SESSION['priority'] = $_POST['priority'];
$_SESSION['inspector']=$_POST['inspectorTxt'];
echo "<pre>";
//print_r($_SESSION);
echo "</pre>";
	
	// For allowing certain image types
	function uploadImage(){
   		$allowedExts = array("jpg", "jpeg", "gif", "png", "JPG", "JPEG","GIF", "PNG");
	   	$extension = end(explode(".", $_FILES["file"]["name"]));
		$UID = uniqid();
		
		if ((($_FILES["file"]["type"] == "image/gif")
			|| ($_FILES["file"]["type"] == "image/jpeg")
			|| ($_FILES["file"]["type"] == "image/JPG")
			|| ($_FILES["file"]["type"] == "image/JPEG")
			|| ($_FILES["file"]["type"] == "image/GIF")
			|| ($_FILES["file"]["type"] == "image/PNG")
			|| ($_FILES["file"]["type"] == "image/png")
			|| ($_FILES["file"]["type"] == "image/pjpeg"))
			&& in_array($extension, $allowedExts))
	   	{
			move_uploaded_file($_FILES["file"]["tmp_name"],
	      				"images/" . $UID . $_FILES["file"]["name"]);
//	      				"images/" . $_FILES["file"]["name"]);


	  	}
	  	return $_FILES["file"]["name"];
 	}
	
	// submit Button is Clicked
	if(isset($_POST['submit']) && $_POST['submit'] == "submit")
	{
		//$inspector = $_POST['inspectorTxt'];
		$inspector = $_SESSION['inspector'];
		$property = $_POST['propertyTxt'];
		$description = $_POST['descriptionTxt'];
		$deficiency = $_POST['deficiencyTxt'];		
		$priority = $_POST['priority'];

//		$filename = uploadImage();
		$filename = uniqid().uploadImage();
		
		//open connection to database
		if (!($connection = @ mysql_connect($hostName, $username, $password)))
			die("Could not connect to database");

		//select database
		if (!mysql_select_db($databaseName, $connection))
			showerror();		
		
		//Build Insert query
		$query = "INSERT INTO inspectiondetails (PropertyId, DeficiencyId, PriorityId, InspectorId, `Description`, Image) VALUES('$property','$deficiency', '$priority', '$inspector', '$description', '$filename')";
		//Process query
		if (!($result = @ mysql_query($query, $connection))) {
			echo "<b>Error in Image Upload.</b><br />";
			var_dump($_FILES);
			echo "query string".$query."<br>";
			echo "connection string".$connection;
			showerror();
		}
		else
		{
			echo "<b>Image Uploaded Successfully.</b><br />";
		}
	}
?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
</head>
<!-- end of Head Section -->

<body>
	<h1>Deficiency Entered</h1>
    <strong>Here is the picture uploaded:</strong>
	<p><img src="images/<?php echo $filename;?>" /><?php echo $_SESSION['property']; ?><?php echo $_SESSION['inspector']; ?><?php echo $_SESSION['deficiency']; ?><?php echo $_SESSION['details']; ?><?php echo $deficiency?></p>
	<p>&nbsp;</p>
	<form id="2">
	<input type="button" value="Enter More " onClick="javascript:location.href = 'Home.php';" />
    <input type="button" value="View All" onClick="javascript:location.href = '../view/viewall.php';" />
</form>
</body>
</html>

Open in new window


and here's the output on the error
Error in Image Upload.
[b]array(1) [/b]{ ["file"]=> array(5) { ["name"]=> string(13) "recycling.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(25) "C:\WINDOWS\Temp\php46.tmp" ["error"]=> int(0) ["size"]=> int(8192) } } 
[b]query string [/b]INSERT INTO inspectiondetails (PropertyId, DeficiencyId, PriorityId, InspectorId, `Description`, Image) VALUES('412C','1', '1', '2', 'test', '526d163ac2471recycling.jpg')
[b]connection[/b] stringResource id #3

Open in new window


I must have changed something last night that is causing my insert to fail.  Anyone see the error.
0
Ray PaseurCommented:
Wow, I see so many errors and omissions I almost don't know where to start.  Let me try to help you get some diagnostic information.

First at the very top of the script add this:

error_reporting(E_ALL);

Next, go through the script and remove the @ notation, so that you can see any and all messages from the functions.

Next, move_uploaded_file() returns a value.  The script should test this for success and create some kind of visualization on failure.

The MySQL database extension is being removed from PHP, so you will want to change to one of the "future-proof" extensions.  This article can help you with that part of it.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Learn about the use of the MySQL escape functions.  This is necessary before external data can be used in a query, and its omission can cause the query to fail.
http://php.net/manual/en/function.mysql-real-escape-string.php
http://php.net/manual/en/mysqli.real-escape-string.php

The content of $_FILES appears to be correct.  You should test the [file] element to see if the upload worked before doing anything else with the uploaded file.  This code snippet shows what errors can be reported.  You can ignore error code 4 if your script has multiple file upload controls - it simply means that the client did not fill in one of the file elements, so you would just skip processing that one.  You can use the reported error code as an index into this array to get the appropriate error message.

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;

Open in new window

From the look of the output, it appears this query may have failed.  Unfortunately, it produces a message that says the file upload failed, and that's a red herring.

if (!($result = @ mysql_query($query, $connection))) {

Here is the correct way to run a query and test for success or failure, with useful information in case of a failure.

// RUN THE QUERY TO CREATE THE TABLE
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = "QUERY FAIL: "
    . $sql
    . ' ERRNO: '
    . mysql_errno()
    . ' ERROR: '
    . mysql_error()
    ;
    trigger_error($err, E_USER_ERROR);
}

Open in new window

Let's start with those changes, and then run the script again so we can see the messages.  It should be easy to find the problem once the correct error reporting is triggered.
0
FSAAdminAuthor Commented:
thanks for continuing to assist with this...I need this in place for say 6-8 months at which point we will be hiring a software company to provide a permanent solution.  

I added this line for error reporting
	echo "error".mysql_errno($query) . ": " . mysql_error($query). "\n";

Open in new window


and the response back is

error: 1265: Data truncated for column 'PropertyId' at row 1

Open in new window


The interesting part is that I didn't touch the database and just last night i was able to insert records into the database without the file upload.
0
Ray PaseurCommented:
That's part of the solution, I'm sure.  But what was in the query that tried to load the PropertyId column?  We don't know. That's why I showed you this way to visualize queries and errors.  You need to be able to see all of it -- otherwise we're just guessing.

It would be helpful to see the CREATE TABLE statement, too.

// HOW TO RUN A QUERY AND TEST FOR ERRORS
$sql = " ... your query string here ...";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = "QUERY FAIL: "
    . $sql
    . ' ERRNO: '
    . mysql_errno()
    . ' ERROR: '
    . mysql_error()
    ;
    trigger_error($err, E_USER_ERROR);
}
                                            

Open in new window

0
Ray PaseurCommented:
It would also be helpful to visualize the contents of the request.  You can add this to the top of the script:

var_dump($_POST);
0
FSAAdminAuthor Commented:
I entered in the error checking and don't get anything displayed.

I added the var_dump($_POST) and this is what I get
array(6) { ["propertyTxt"]=> string(4) "412C" ["deficiencyTxt"]=> string(1) "1" ["descriptionTxt"]=> string(0) "" ["priority"]=> string(1) "1" ["inspectorTxt"]=> string(1) "2" ["submit"]=> string(6) "submit" } 

Open in new window


Here's what my script looks like now
<?php
error_reporting(E_ALL);
$filename = "";
$status = 0;
session_start();
$_SESSION['property'] = $_POST['propertyTxt'];
$_SESSION['deficiency'] = $_POST['deficiencyTxt'];
$_SESSION['details'] = $_POST['descriptionTxt'];
$_SESSION['priority'] = $_POST['priority'];
$_SESSION['inspector']=$_POST['inspectorTxt'];
echo "<pre>";
//print_r($_SESSION);
echo "</pre>";
	
	// For allowing certain image types
	function uploadImage(){
   		$allowedExts = array("jpg", "jpeg", "gif", "png", "JPG", "JPEG","GIF", "PNG");
	   	$extension = end(explode(".", $_FILES["file"]["name"]));
		$UID = uniqid();
		
		if ((($_FILES["file"]["type"] == "image/gif")
			|| ($_FILES["file"]["type"] == "image/jpeg")
			|| ($_FILES["file"]["type"] == "image/JPG")
			|| ($_FILES["file"]["type"] == "image/JPEG")
			|| ($_FILES["file"]["type"] == "image/GIF")
			|| ($_FILES["file"]["type"] == "image/PNG")
			|| ($_FILES["file"]["type"] == "image/png")
			|| ($_FILES["file"]["type"] == "image/pjpeg"))
			&& in_array($extension, $allowedExts))
	   	{
			move_uploaded_file($_FILES["file"]["tmp_name"],
	      				"images/" . $UID . $_FILES["file"]["name"]);
//	      				"images/" . $_FILES["file"]["name"]);


	  	}
	  	return $_FILES["file"]["name"];
 	}
	
	// submit Button is Clicked
	if(isset($_POST['submit']) && $_POST['submit'] == "submit")
	{
		$inspector = $_POST['inspectorTxt'];
		//$inspector = $_SESSION['inspector'];
		$property = $_POST['propertyTxt'];
		//$property = $_SESSION['property'];
		$description = $_POST['descriptionTxt'];
		//$description = $_SESSION['descriptoin'];
		$deficiency = $_POST['deficiencyTxt'];
		//$deficieicny = $_SESSION['deficiency'];		
		$priority = $_POST['priority'];
		//$priority = $_SESSION['priority'];

//		$filename = uploadImage();
		$filename = uniqid().uploadImage();
		var_dump($_POST);
		// HOW TO RUN A QUERY AND TEST FOR ERRORS
$sql = "INSERT INTO inspectiondetails (PropertyId, DeficiencyId, PriorityId, InspectorId, `Description`, Image) VALUES('$property','$deficiency', '$priority', '$inspector', '$description', '$filename')";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = "QUERY FAIL: "
    . $sql
    . ' ERRNO: '
    . mysql_errno()
    . ' ERROR: '
    . mysql_error()
    ;
    trigger_error($err, E_USER_ERROR);
}
		//open connection to database
		if (!($connection = @ mysql_connect($hostName, $username, $password)))
			die("Could not connect to database");

		//select database
		if (!mysql_select_db($databaseName, $connection))
			showerror();		
		
		//Build Insert query
		$query = "INSERT INTO inspectiondetails (PropertyId, DeficiencyId, PriorityId, InspectorId, `Description`, Image) VALUES('$property','$deficiency', '$priority', '$inspector', '$description', '$filename')";
		//Process query
		if (!($result = @ mysql_query($query, $connection))) {
			echo "<b>Error in Image Upload.</b><br />";
			var_dump($_FILES);
			echo "query string".$query."<br>";
			echo "connection string".$connection;
			echo $property.$deficieicny.$priority.$inspector.$description.$filename;
			echo "error".mysql_errno($query) . ": " . mysql_error($query). "\n";
			echo mysql_errno($connection) . ": " . mysql_error($connection). "\n";
			showerror();
		}
		else
		{
			echo "<b>Image Uploaded Successfully.</b><br />";
		}
	}
?>

Open in new window

0
Ray PaseurCommented:
PHP scripts run the instructions from the top to the bottom, unless there is a deliberate control structure to change the order of instructions.  Some things have to come first, for example, you need to connect to the data base server and select the data base before you can run a query.  So the code now appears to be out of order.  That's the sort of thing that can happen when we try to patch something that doesn't work -- it's often better to start over and rebuild rather than try to figure out everything at once.

Can you tell me why the PHP session is being used in this script?

Can you please post the CREATE TABLE statement for the inspectiondetails?

Thanks, ~Ray
0
FSAAdminAuthor Commented:
I never create the table inspectiondetails.  The table has already been created, I'm only inserting a record into the table.  The insert statement is:

"INSERT INTO inspectiondetails (PropertyId, DeficiencyId, PriorityId, InspectorId, `Description`, Image) VALUES('$property','$deficiency', '$priority', '$inspector', '$description', '$filename')"

Open in new window


The reason for using sessions is that the users will go through a series of forms and select values for all the variables except the $filename.  If you recall, this is a system we are building to be used on a tablet, so we have the users going through a series of selection menus to update their content.  

Here's a link to test form I'm using now:  http;//bfwebdev.nmsu.edu/FCAInspection/exchange/Home.php

First step is to select the inspector.  Second step is to select a facility/property.  I've displayed the selections on forms to be sure the values are being passed over.  The third step is to complete the inspection form.  I've made this as generic as possible as we though that jquery was causing problems for us.  But after selecting a system/deficiency combination, the user would then choose to upload an image (when doing this on the tablet the user is allowed to take a picture or upload from existing images).
0
Ray PaseurCommented:
I never create the table inspectiondetails...
That does not matter.  You can run the SHOW CREATE TABLE query to get the CREATE TABLE statement.  We need to see the column definitions to be able to understand the error messages.

The reason I asked about the PHP session is that you do not extract any information from it in this script.  So I'm guessing that this script is not the last in the cascade?

Are you sure you want to wait 6-8 months to get a software company involved?  This would go a lot faster (perhaps be completed in a few hours) by a professional programmer.  The reason this is taking a long time is that you have to learn all the things a professional programmer already knows, and learning by trial and error (especially copying DreamWeaver code) is a really tough way to go.  It's like trying to learn to bake by looking at an apple pie.  You can appreciate the pie for what it is, but that tells you nothing of the processes and tools that were used by the experienced baker.

You might be better off starting with this (even if you will still have to convert it to MySQLi or PDO).  If you read it and do not understand something, please post back and I'll try to explain.  Obviously since I do not have your data base, it is untested code, so please do not use it until you have evaluated it for suitability in your environment.

<?php // RAY_temp_fsaadmin.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
session_start();

// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";

// CONNECT AND SELECT DATA BASE
// OPEN A CONNECTION TO THE DATA BASE SERVER
if (!$dbcon = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $err
    = "NO DB CONNECTION: $db_host: "
    . mysql_errno()
    . ' '
    . mysql_error()
    ;
    trigger_error($err, E_USER_WARNING);
}

// SELECT THE MYSQL DATA BASE
if (!mysql_select_db($db_name, $dbcon))
{
    $err
    = "NO DB SELECTION: $db_name: "
    . mysql_errno()
    . ' '
    . mysql_error()
    ;
    trigger_error($err, E_USER_WARNING);
    trigger_error('NO DATABASE', E_USER_ERROR);
}

// COPY SOME VALUES INTO THE SESSION AND ESCAPE FOR USE IN A QUERY
$_SESSION['property']   = $_POST['propertyTxt'];
$_SESSION['deficiency'] = $_POST['deficiencyTxt'];
$_SESSION['details']    = $_POST['descriptionTxt'];
$_SESSION['priority']   = $_POST['priority'];
$_SESSION['inspector']  = $_POST['inspectorTxt'];

$property    = mysql_real_escape_string($_SESSION['property']);
$deficiency  = mysql_real_escape_string($_SESSION['deficiency']);
$description = mysql_real_escape_string($_SESSION['details']);
$priority    = mysql_real_escape_string($_SESSION['priority']);
$inspector   = mysql_real_escape_string($_SESSION['inspector']);

// GET A UNIQUE ID AND A FILE NAME
$uniq = uniqid();
$file = $uniq . $_FILES['file']['name'];

// SAVE THE FILE
if (!move_uploaded_file($_FILES['file']['tmp_name'], 'images' . DIRECTORY_SEPARATOR . $file))
{
    trigger_error('move_uploaded_file FAILED', E_USER_ERROR);
}

// BUILD THE QUERY
$sql
=
"
INSERT INTO inspectiondetails
( PropertyId
, DeficiencyId
, PriorityId
, InspectorId
, `Description`
, Image
) VALUES
( '$property'
, '$deficiency'
, '$priority'
, '$inspector'
, '$description'
, '$file'
)
"
;
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = "QUERY FAIL: "
    . $sql
    . ' ERRNO: '
    . mysql_errno()
    . ' ERROR: '
    . mysql_error()
    ;
    trigger_error($err, E_USER_ERROR);
}

Open in new window

0
FSAAdminAuthor Commented:
Here's the details of Show Create Table for the inspectiondetails

inspectiondetails	

CREATE TABLE `inspectiondetails` (
  `idInspectionDetails` int(11) NOT NULL AUTO_INCREMENT,
  `PropertyId` int(11) DEFAULT NULL,
  `SystemsId` int(11) DEFAULT NULL,
  `DeficiencyId` int(11) DEFAULT NULL,
  `PriorityId` int(11) DEFAULT NULL,
  `InspectorId` int(11) DEFAULT NULL,
  `InspectionDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `Description` varchar(500) DEFAULT NULL,
  `Image` varchar(50) DEFAULT NULL,
  `StatusId` int(11) DEFAULT NULL,
  `EstimateCost` decimal(10,2) DEFAULT NULL,
  `EstimateDate` datetime DEFAULT NULL,
  PRIMARY KEY (`idInspectionDetails`),
  UNIQUE KEY `idInspectionDetails_UNIQUE` (`idInspectionDetails`)
) ENGINE=InnoDB AUTO_INCREMENT=599 DEFAULT CHARSET=utf8 COMMENT='Inspection Details'

Open in new window

0
FSAAdminAuthor Commented:
error message on the sample page you posted after I entered the correct db parameters:

Fatal error: QUERY FAIL: INSERT INTO inspectiondetails ( PropertyId , DeficiencyId , PriorityId , InspectorId , `Description` , Image ) VALUES ( '412C' , '1' , '1' , '2' , 'test' , '526d7dc2f4000187.jpg' ) ERRNO: 1265 ERROR: Data truncated for column 'PropertyId' at row 1 in C:\WebPub\FCAInspection\exchange\index6b.php on line 95

Open in new window

0
Ray PaseurCommented:
Column "PropertyId" is defined as an integer field.  The script tried to insert '412C' hence the error.

Please consider hiring a professional programmer with experience in PHP software development.  This is going to be too long a road if you try to go it alone.

Best of luck, over and out, ~Ray
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
FSAAdminAuthor Commented:
nice catch...I switched the value of to the text so we could see the property.  Now I switched it to the ID field (int) and it worked.  Thank you so much for your help.

Now I'm going to spend some time trying to format the last page with Jquery Mobile and keep my fingers crossed nothing breaks.

I appreciate your help greatly Ray.
0
FSAAdminAuthor Commented:
Thank you
0
Ray PaseurCommented:
Thanks for the points and best of luck with it, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Scripting Languages

From novice to tech pro — start learning today.