表单操作字段无法一起上传和移动到新页面

时间:2014-06-20 14:40:51

标签: php mysql html5 forms mysqli

编辑:@James解决方案的答案在下面的代码中加粗。 再次感谢@James。


我有一个表单(HTML),它有一个文本字段并将文件上传到数据库。 在我使用之前

    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" name="form1" enctype="multipart/form-data"></pre>

它工作正常,现在我希望页面将条目提交到数据库并显示不同的页面,所以我尝试了这个

    <form action="page3.php"......>, but didn't worked.

但是,当我单击“提交”按钮时,它会在数据库中输入文本字段,但不会将文件上载到数据库。 我想要它做的是:当我点击提交按钮时,文本字段被输入数据库,文件被上传到数据库文件夹(我的程序使其路径进入数据库),以及为用户加载的新页面

感谢任何帮助。谢谢。 我的PHP代码

    <?php

    //ob_start();
    $host="localhost";
    $username="root";
    $password="";
    $db_name="newrep";
    $table_name="members";

    $conn=new mysqli('localhost','root','','newrep');
    if(!$conn){
        die("cannot connect.");
    }
    //else if(!mysql_select_db($db_name)){
      //  die(" cannot select database.");
    //}

    session_start();
    use foundationphp\UploadFile;
    echo "Session value: ".$_SESSION['texas'];
    $currentuser=$_SESSION['texas'];
     echo $currentuser;
     $current_year=date("Y");

     //code for upload starts here
    require_once 'src/foundationphp/UploadFile.php';
    if (!isset($_SESSION['maxfiles'])) {
    $_SESSION['maxfiles'] = ini_get('max_file_uploads');
    $_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
    $_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
    }
    $max = 2048 * 1024;
    $result = array();
    //upload code ended above
    if(!isset($_SESSION['texas'])) 
    {
      header('Location:login_page.php');
      exit();
   }
   else {
    if(isset($_POST['title'])){
      echo "reaching the else";
      if(isset($_POST['upload'])){
      //upload in POST is for upload
        print_r($_FILES);
      $destination = __DIR__ . '/uploaded/'; //for upload
      //upload code try and catch
      try {
      $upload = new UploadFile($destination);
      $upload->setMaxSize($max);
      //$upload->allowAllTypes();
      $upload->upload();
      $result = $upload->getMessages();
        } 
      catch (Exception $e) {
        $result[] = $e->getMessage();
        }
      } 
    $error = error_get_last();
    if ($result || $error){ 
    //<ul class="result">
    if ($error){
    echo "{$error['message']}"; }
    if ($result) {
    foreach ($result as $message) {
    echo "<li>$message</li>";}}}

    $file_path_variable= $destination.$_SESSION['current_filename'];
    echo $file_path_variable;

    $title=$_POST['title'];

    $query="INSERT INTO proposal(title_prop, userName_prop,whitepaper_prop,year_prop) VALUES('$title','$currentuser','$file_path_variable','$current_year')";

    $result_query=mysqli_query($conn,$query);

   echo "      in elseif         ";
    if(!$result_query){
      echo " cannot insert ";
    }
    else {
**header('Location: page3.php');
exit();**
      //echo "successful entry ";
    }
   }
    //ob_end_flush();    
 ?>

HTML代码:

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Online Application</title>
  <!--  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> -->
  <link href="bootstrap.min.css" rel="stylesheet">
<head><script src="bootstrap.min.js"></script> </head>
<body>
    <div id="O_o"><br><h4>Texas State University</h4></div>
<div id="wrapper">
      <form action=**"<?php $_SERVER['PHP_SELF']?>"** method="POST" id="whitepaper" name="whitepaper" role="form" enctype="multipart/form-data">
<legend><h5><b>Online Application</b></h5></legend>

          <h4 id="reference" name="reference" class="heading-reference"><b>Proposal Whitepaper</b></h4>

<fieldset>
<center>
<div class="form-group">
 <?php echo "Year of Proposal: $current_year";?><br> 
<label class="label_title control-label" for="title">Submit Title of your proposal:</label>
<input id="title" name="title" type="text" placeholder="" class="input_title form-control" >
<p class="help-block">All fields are required.</p><!--
<button type="submit" id="submit_button" name="btn-primary" class="btn btn-primary"> Submit Title </button>-->
</div>



<div class="form-group">
<label class="label_whitepaper control-label" for="file">Upload the whitepaper of your proposal here: <br>Only .docx , .doc and .pdf format extensions are permitted.</label>

<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">

<p><input type="file" id="filename" name="filename[]" title="Browse for whitepaper" class="btn-primary" multiple
  data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
  data-postmax="<?php echo $_SESSION['postmax'];?>"
  data-displaymax="<?php echo $_SESSION['displaymax'];?>"></p>

File should be no more than <?php echo UploadFile::convertFromBytes($max);?>.<br>
<!--<p><input type="submit" name="upload" value="Upload File" class="btn-primary">-->
<button id="submit" name="upload" class="btn-primary" >Submit and continue</button>
</div>

</center>


</fieldset>
</form>
</div>
<script src="js/checkmultiple.js"></script>
<script src="jquery.min.js"></script>
<script src="prettify.js"></script>
<script src="bootstrap.file-input.js"></script>
<script>
$(document).ready(function(){
  $('input[type=file]').bootstrapFileInput();
});
</script>
</body>
</html>
<?php } 
mysqli_close($conn);
?>

1 个答案:

答案 0 :(得分:0)

您需要在表单标记中加入enctype='multipart/form-data'

<form action='<?php echo $_SERVER['PHP_SELF']?>' method="POST" name="form1" enctype='multipart/form-data'>

没有它,附件就无法通过表单发送。

<强>更新

尝试以下代码。我也修复了一些HTML错误。

<?php

    //ob_start();
    $host="localhost";
    $username="root";
    $password="";
    $db_name="newrep";
    $table_name="members";

    $conn=new mysqli('localhost','root','','newrep');
    if(!$conn){
        die("cannot connect.");
    }
    //else if(!mysql_select_db($db_name)){
      //  die(" cannot select database.");
    //}

    session_start();
    use foundationphp\UploadFile;
    echo "Session value: ".$_SESSION['texas'];
    $currentuser=$_SESSION['texas'];
    echo $currentuser;
    $current_year=date("Y");

    //code for upload starts here
    require_once 'src/foundationphp/UploadFile.php';
    if (!isset($_SESSION['maxfiles'])) {
        $_SESSION['maxfiles'] = ini_get('max_file_uploads');
        $_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
        $_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
    }

    $max = 2048 * 1024;
    $result = array();
    //upload code ended above
    if(!isset($_SESSION['texas'])) 
    {
        header('Location:login_page.php');
        exit();
    }else {
        if(isset($_POST['title'])){
            echo "reaching the else";
            if(isset($_POST['upload'])){
                //upload in POST is for upload
                print_r($_FILES['fieldname']);
                $destination = __DIR__ . '/uploaded/'; //for upload
                //upload code try and catch
                try {
                    $upload = new UploadFile($destination);
                    $upload->setMaxSize($max);
                    //$upload->allowAllTypes();
                    $upload->upload();
                    $result = $upload->getMessages();
                }catch (Exception $e) {
                    $result[] = $e->getMessage();
                }
            } 
            $error = error_get_last();
            if ($result || $error){ 
                //<ul class="result">
                if ($error){
                    echo "{$error['message']}"; }
                if ($result) {
                    foreach ($result as $message) {
                    echo "<li>$message</li>";
                    }
                }
            }

            $file_path_variable= $destination.$_SESSION['current_filename'];
            //echo $file_path_variable;

            $title=$_POST['title'];

            $query="INSERT INTO proposal(title_prop, userName_prop,whitepaper_prop,year_prop) VALUES('$title','$currentuser','$file_path_variable','$current_year')";

            $result_query=mysqli_query($conn,$query);

            //echo "      in elseif         ";
            if(!$result_query){
                echo " cannot insert ";
            }else {
                header('Location: page3.php');
                exit();
                //echo "successful entry ";
            }
        }
        //ob_end_flush();    
        ?>

        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">

                <title>Online Application</title>
                <!--  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> -->
                <link href="bootstrap.min.css" rel="stylesheet">
                <script src="bootstrap.min.js"></script>
            </head>
            <body>
                <div id="O_o"><br><h4>Texas State University</h4></div>
                <div id="wrapper">
                    <form action="<?php= $_SERVER['PHP_SELF']?>" method="POST" id="whitepaper" name="whitepaper" role="form" enctype="multipart/form-data">
                        <fieldset>
                            <legend><h5><b>Online Application</b></h5></legend>

                            <h4 id="reference" name="reference" class="heading-reference"><b>Proposal Whitepaper</b></h4>
                            <center>
                                <div class="form-group">
                                    <?php echo "Year of Proposal: $current_year";?><br> 
                                   <label class="label_title control-label" for="title">Submit Title of your proposal:</label>
                                   <input id="title" name="title" type="text" placeholder="" class="input_title form-control" >
                                   <p class="help-block">All fields are required.</p><!--
                                   <button type="submit" id="submit_button" name="btn-primary" class="btn btn-primary"> Submit Title </button>-->
                                </div>

                                <div class="form-group">
                                    <label class="label_whitepaper control-label" for="file">Upload the whitepaper of your proposal here: <br>Only .docx , .doc and .pdf format extensions are permitted.</label>

                                    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">

                                    <p><input type="file" id="filename" name="filename[]" title="Browse for whitepaper" class="btn-primary" multiple
                                      data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
                                      data-postmax="<?php echo $_SESSION['postmax'];?>"
                                      data-displaymax="<?php echo $_SESSION['displaymax'];?>"></p>

                                    File should be no more than <?php echo UploadFile::convertFromBytes($max);?>.<br>
                                    <!--<p><input type="submit" name="upload" value="Upload File" class="btn-primary">-->
                                    <button id="submit" name="upload" class="btn-primary" >Submit and continue</button>
                                </div>
                            </center>
                        </fieldset>
                    </form>
                </div>

                <script src="js/checkmultiple.js"></script>
                <script src="jquery.min.js"></script>
                <script src="prettify.js"></script>
                <script src="bootstrap.file-input.js"></script>
                <script>
                    $(document).ready(function(){
                        $('input[type=file]').bootstrapFileInput();
                    });
                </script>
            </body>
        </html>
    <? } 
    mysqli_close($conn);
?>