We help IT Professionals succeed at work.

Can't get upload AND insert to DB to work on same page.

absolut_joe
absolut_joe asked
on
362 Views
Last Modified: 2013-12-13
I am trying to use PHP to upload a video to my site, then insert data about the video to a DB.  I have code for each that works by themselves, but I cannot call them consecutively.  Right now, it does not do the DB insert, only the upload.  What do I need to do.  I've included the two sets of code on the upload page below - but only the upload function is executing.

UPLOAD CODE-------------------------------------------------------
if (phpversion() > "4.0.6") {
      $HTTP_POST_FILES = &$_FILES;
}
define("MAX_SIZE",0);
define("DESTINATION_FOLDER", "/home/pushbutt/public_html/newvideos");
define("no_error", "UploadSuccess.php");
define("yes_error", "UploadFailed.php");
$_accepted_extensions_ = "";

if(strlen($_accepted_extensions_) > 0){
      $_accepted_extensions_ = @explode(",",$_accepted_extensions_);
}
else {
      $_accepted_extensions_ = array();
}

$_file_ = $HTTP_POST_FILES['UploadFile'];

if(is_uploaded_file($_file_['tmp_name']) && $HTTP_POST_FILES['UploadFile']['error'] == 0){
      $errStr = "";
      $_name_ = $_file_['name'];
      $_type_ = $_file_['type'];
      $_tmp_name_ = $_file_['tmp_name'];
      $_size_ = $_file_['size'];
      
      if($_size_ > MAX_SIZE && MAX_SIZE > 0){
            $errStr = "File too large";
      }
      
      $_ext_ = explode(".", $_name_);
      $_ext_ = strtolower($_ext_[count($_ext_)-1]);
      
      if(!in_array($_ext_, $_accepted_extensions_) && count($_accepted_extensions_) > 0){
            $errStr = "Extension not valid";
      }
      
      if(!is_dir(DESTINATION_FOLDER) && is_writeable(DESTINATION_FOLDER)){
            $errStr = "Destination folder not valid.";
      }
      if(empty($errStr)){
            if(@copy($_tmp_name_,DESTINATION_FOLDER . "/" . $_name_)){
                  //header("Location: " . no_error);
            } else {
                  header("Location: " . yes_error);
            }
      } else {
            header("Location: " . yes_error);
      }
}



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

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO SubmittedVideos (VideoDirector, VideoName, VideoPath, AccountID, VideoReleaseAccepted) VALUES (%s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['FormDirectorSpry'], "text"),
                       GetSQLValueString($_POST['FormFilmNameText'], "text"),
                       GetSQLValueString($_POST['UploadFile'], "text"),
                       GetSQLValueString($_POST['HiddenAccountID'], "text"),
                       GetSQLValueString(isset($_POST['FormReleaseCheck']) ? "true" : "", "defined","'Y'","'N'"));

  mysql_select_db($database_SubmittedVideos, $SubmittedVideos);
  $Result1 = mysql_query($insertSQL, $SubmittedVideos) or die(mysql_error());

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

FORM ACTION CODE ------------------------------------------------------
<form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="form1" class="l_text">



What am I doing wrong here?
Comment
Watch Question

Commented:
take out the redirect and see if you get any errors

are the database values set to NULL or NOT NULL?
if you set them to not null for testing puposes, then sometimes, it will give you an idea of what is messing up.

Author

Commented:
I believe that skipping the "success" redirects worked, but it now has another issue.  When it hits the insert, it fails out because there is no data in the file upload box.  For some reason, the box gets blanked out during the upload process.  How can I save that field to a hidden session variable before that happens?  Are there special considerations for file upload boxes?

Commented:
do you mean when you update the record?

ok basically you need to make the filename a hidden variable in the form.
hope that helps.
gotta head off to bed, so I can't look into it too much right now.
hope u get it sorted out.
cheers

Author

Commented:
I have set that up, but I can't get the text value of the upload file box into the session.  I'll post the code when I get home.

Author

Commented:
Here is ALL the php (I hate to post it, but I can't figure out how/where to get the hidden session variable set.

PHP----------------------------------------------------------------
if (phpversion() > "4.0.6") {
      $HTTP_POST_FILES = &$_FILES;
}
define("MAX_SIZE",0);
define("DESTINATION_FOLDER", "/home/pushbutt/public_html/newvideos");
define("no_error", "UploadSuccess.php");
define("yes_error", "UploadFailed.php");
$_accepted_extensions_ = "";

if(strlen($_accepted_extensions_) > 0){
      $_accepted_extensions_ = @explode(",",$_accepted_extensions_);
}
else {
      $_accepted_extensions_ = array();
}

//$_SESSION['MM_FileUpload'] = $_POST['UploadFile'];
$_file_ = $HTTP_POST_FILES['UploadFile'];


if(is_uploaded_file($_file_['tmp_name']) && $HTTP_POST_FILES['UploadFile']['error'] == 0){
      $errStr = "";
      $_name_ = $_file_['name'];
      $_type_ = $_file_['type'];
      $_tmp_name_ = $_file_['tmp_name'];
      $_size_ = $_file_['size'];
      
      
      if($_size_ > MAX_SIZE && MAX_SIZE > 0){
            $errStr = "File too large";
      }
      
      $_ext_ = explode(".", $_name_);
      $_ext_ = strtolower($_ext_[count($_ext_)-1]);
      
      if(!in_array($_ext_, $_accepted_extensions_) && count($_accepted_extensions_) > 0){
            $errStr = "Extension not valid";
      }
      
      if(!is_dir(DESTINATION_FOLDER) && is_writeable(DESTINATION_FOLDER)){
            $errStr = "Destination folder not valid.";
      }
      if(empty($errStr)){
            if(@copy($_tmp_name_,DESTINATION_FOLDER . "/" . $_name_)){
                  //header("Location: " . no_error);
            } else {
                  header("Location: " . yes_error);
            }
      } else {
            header("Location: " . yes_error);
      }
}
//end upload ------------------------------------------------------------------------


//Check if logged in
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}


$UsernameSession_IsLoggedInQry = "0";
if (isset($_SESSION['MM_Username'])) {
  $UsernameSession_IsLoggedInQry = $_SESSION['MM_Username'];
}
mysql_select_db($database_Login, $Login);
$query_IsLoggedInQry = sprintf("SELECT AccountUsername FROM Accounts WHERE AccountUsername = %s", GetSQLValueString($UsernameSession_IsLoggedInQry, "text"));
$IsLoggedInQry = mysql_query($query_IsLoggedInQry, $Login) or die(mysql_error());
$row_IsLoggedInQry = mysql_fetch_assoc($IsLoggedInQry);
$totalRows_IsLoggedInQry = mysql_num_rows($IsLoggedInQry);
//end check for login  -----------------------------------------------------------------------------



//----------Insert into Submitted Videos table--------------------------------------
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO SubmittedVideos (VideoDirector, VideoName, VideoPath, AccountID, VideoReleaseAccepted) VALUES (%s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['FormDirectorSpry'], "text"),
                       GetSQLValueString($_POST['FormFilmNameText'], "text"),
                       GetSQLValueString($_POST['HiddenPath'], "text"),
                       GetSQLValueString($_POST['HiddenAccountID'], "text"),
                       GetSQLValueString(isset($_POST['FormReleaseCheck']) ? "true" : "", "defined","1","0"));

  mysql_select_db($database_Login, $Login);
  $Result1 = mysql_query($insertSQL, $Login) or die(mysql_error());

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

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><!-- InstanceBegin template="/Templates/GeneralTemplate.dwt" codeOutsideHTMLIsLocked="false" -->
<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- InstanceBeginEditable name="doctitle" -->
<title>PushButton Films - The fastest way to new movies</title>
<!-- InstanceEndEditable -->
<script language="JavaScript" type="text/JavaScript">
<!--
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
END----------------------------------------------------------------------

I have commented out where I am trying to set the session variable to later use in the DB insert.  It just isn't working.  PLEASE HELP!

Commented:
first thing you need to do is put
session_start();
at the start of your document.
sessions will not work without it.

Commented:
is it only the filename that is not being inserted into the database?

Author

Commented:
1.  I added the "session_start(); with no avail.  Is my assignment statment to get the path into the session wrong?
2.  The page errors out to say "VideoPath cannot be null" so the entire insert statement does not work.  Is something with the upload function clearing out the file path from the file upload box?

Commented:
in your form, do you have a field for HiddenPath ?
that is not being entered into the database for some reason.

Commented:
i can't see anywhere where it is set in the code you provided.

as I said in my first comment, for testing purposes it is a good idea to set all the fields in the table to NULL, instead of NOT NULL,
so you can see which parts of the insert aren't working then concentrate on fixing those.

Author

Commented:
Here it is in the code above.  In my working copy, I've un-commented it and added the session start code.  This is located up in the Upload section as I thought that I need to assign it before it gets out of that function or risk losing the value.

Thoughts?

$_SESSION['MM_FileUpload'] = $_POST['UploadFile'];
$_file_ = $HTTP_POST_FILES['UploadFile'];

Author

Commented:
Yes, when I set the DB to allow nulls, only the file upload box does not transfer the data.  I've reposted the code below.

---------Start code----------------------------

<?php require_once('../Connections/Login.php'); ?>
<?php
//      ---------------------------------------------
//      Pure PHP Upload version 1.1
//      -------------------------------------------
session_start();

if (phpversion() > "4.0.6") {
      $HTTP_POST_FILES = &$_FILES;
}
define("MAX_SIZE",0);
define("DESTINATION_FOLDER", "/home/pushbutt/public_html/newvideos");
define("no_error", "UploadSuccess.php");
define("yes_error", "UploadFailed.php");
$_accepted_extensions_ = "";

if(strlen($_accepted_extensions_) > 0){
      $_accepted_extensions_ = @explode(",",$_accepted_extensions_);
}
else {
      $_accepted_extensions_ = array();
}

$_SESSION['MM_FileUpload'] = $_POST['UploadFile'];
$_file_ = $HTTP_POST_FILES['UploadFile'];


if(is_uploaded_file($_file_['tmp_name']) && $HTTP_POST_FILES['UploadFile']['error'] == 0){
      $errStr = "";
      $_name_ = $_file_['name'];
      $_type_ = $_file_['type'];
      $_tmp_name_ = $_file_['tmp_name'];
      $_size_ = $_file_['size'];
      
      
      if($_size_ > MAX_SIZE && MAX_SIZE > 0){
            $errStr = "File too large";
      }
      
      $_ext_ = explode(".", $_name_);
      $_ext_ = strtolower($_ext_[count($_ext_)-1]);
      
      if(!in_array($_ext_, $_accepted_extensions_) && count($_accepted_extensions_) > 0){
            $errStr = "Extension not valid";
      }
      
      if(!is_dir(DESTINATION_FOLDER) && is_writeable(DESTINATION_FOLDER)){
            $errStr = "Destination folder not valid.";
      }
      if(empty($errStr)){
            if(@copy($_tmp_name_,DESTINATION_FOLDER . "/" . $_name_)){
                  //header("Location: " . no_error);
            } else {
                  header("Location: " . yes_error);
            }
      } else {
            header("Location: " . yes_error);
      }
}
//end upload ------------------------------------------------------------------------


//Check if logged in
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}


$UsernameSession_IsLoggedInQry = "0";
if (isset($_SESSION['MM_Username'])) {
  $UsernameSession_IsLoggedInQry = $_SESSION['MM_Username'];
}
mysql_select_db($database_Login, $Login);
$query_IsLoggedInQry = sprintf("SELECT AccountUsername FROM Accounts WHERE AccountUsername = %s", GetSQLValueString($UsernameSession_IsLoggedInQry, "text"));
$IsLoggedInQry = mysql_query($query_IsLoggedInQry, $Login) or die(mysql_error());
$row_IsLoggedInQry = mysql_fetch_assoc($IsLoggedInQry);
$totalRows_IsLoggedInQry = mysql_num_rows($IsLoggedInQry);
//end check for login  -----------------------------------------------------------------------------



//----------Insert into Submitted Videos table--------------------------------------
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO SubmittedVideos (VideoDirector, VideoName, VideoPath, AccountID, VideoReleaseAccepted) VALUES (%s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['FormDirectorSpry'], "text"),
                       GetSQLValueString($_POST['FormFilmNameText'], "text"),
                       GetSQLValueString($_POST['HiddenPath'], "text"),
                       GetSQLValueString($_POST['HiddenAccountID'], "text"),
                       GetSQLValueString(isset($_POST['FormReleaseCheck']) ? "true" : "", "defined","1","0"));

  mysql_select_db($database_Login, $Login);
  $Result1 = mysql_query($insertSQL, $Login) or die(mysql_error());

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

?>

Commented:
so is the file being uploaded at all?

can i also see the form. something is not being passed from the form to the script.
which one of these is not being filled?
VideoDirector, VideoName, VideoPath, AccountID, VideoReleaseAccepted

Author

Commented:
Yes, the file is getting uploaded. It just isn't passing the path to the DB.  I've posed the form below.


-----------------Form Below----------------------------------------------------------------------------------------

<form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="form1" class="l_text">
              <p>
                 <label></label>
              </p>
              <p>
                <span id="sprytextfield1">
                  <label>Director
                  <input type="text" name="FormDirectorSpry" id="FormDirectorSpry">
                  </label>
                <span class="textfieldRequiredMsg">You must fill in a Diretor name.</span>
                </span>
              </p>
              <p>
                <span id="sprytextfield2">
                  <label>Film Name</label>
                  <input type="text" name="FormFilmNameText" id="FormFilmNameText">
                <span class="textfieldRequiredMsg">You must fill in a film name.</span>                </span>              
              </p>
              <p>
                 <input name="UploadFile" type="file" class="lh" id="UploadFile" style="background-color:#FFFFFF font-color:#000000">
              </p>
              <p class="lh">
                    <span id="sprycheckbox1">
                            <input type="checkbox" name="FormReleaseCheck" id="FormReleaseCheck">
                  <label>I agree to terms</label>
                          <span class="checkboxRequiredMsg">You must accept the terms in order to allow Push Button films to show your film.</span>                </span>              </p>
                    <p>
                          <label>
                            <input type="submit" name="UploadButton" id="UploadButton" value="Submit">
                      </label>
                    </p>
                    <input type="hidden" name="MM_insert" value="form1">
              <input name="HiddenAccountID" type="hidden" id="HiddenAccountID" value="<?php echo $_SESSION['MM_AccountID']; ?>">
              <input type="hidden" name="HiddenPath" id="HiddenPath" value="<?php echo $_SESSION['MM_FileUpload']; ?>">
              </form>
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
YES!!! I used the "GetSQLValueString($_name_ , "text")," text and it worked.  Thanks much for everyone who looked at it.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.