【问题标题】:PHP: input field not getting cleared after the form is SubmittedPHP:提交表单后输入字段未清除
【发布时间】:2014-03-15 06:57:48
【问题描述】:

提交表单后显示

“您的数据已提交,我们会尽快与您联系!!”

同时,表单输入字段保留在页面中(字段上仍然存在提交的数据)

提交后如何清除输入字段中的数据

这是我的代码:

  <?php
        if(isset($_POST['name']))
{

    include_once("config.php");

    $name=$email=$phone=$uploadresume="";
    $nameErr=$emailErr=$phoneErr=$uploadresumeErr="";


    function test_input($data)
    {
        $data=trim($data);
        $data=stripslashes($data);
        $data=htmlspecialchars($data);
        return $data;
    }
if ($_SERVER['REQUEST_METHOD']=="POST"){

    $valid=true;
        //name validaton
        if(empty($_POST["name"]))
        {
            $nameErr="* Name is Required";
            $valid=false;
        }
        else
        {
            $name=test_input($_POST["name"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$name))
     {
      $nameErr = "&nbsp;&nbsp;Only letters and white space allowed"; 
      $valid=false;
     }
        }

            //Email Address validaton
        if(empty($_POST["email"]))
        {
            $emailErr="* Email is Required";
            $valid=false;
        }
        else
        {
            $email=test_input($_POST["email"]);
       if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
       {
           $emailErr="&nbsp;&nbsp; Enter a valid Email ID";
           $valid=false;
       }
        }

        //Mobile no validaton
        if(empty($_POST["phone"]))
        {
            $phoneErr="* Mobile no is Required";
            $valid=false;
        }
        else
        {
            $phone=test_input($_POST["phone"]);
             if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) 
       {
        $phoneErr="*Enter a valid contact no";
        $valid=false;
       }    
        }


        if(empty($_FILES["filename"]['name'])) 
{ 
$uploadresumeErr="* Upload Your Resume"; 
$valid=false; 
} 
else 
{
     $fname_arr = explode('.',$_FILES["filename"]['name']);
      $fileext = $fname_arr[count($fname_arr)-1]; 
      $ext_arr = array('doc','pdf'); 
      if(in_array($fileext,$ext_arr))
      { 
      $uploadresume=test_input($_POST["filename"]);
      }
      else{
        $uploadresumeErr="* Upload only doc or pdf files.";
        $valid=false; 
         } 
         } 


    if($valid)
 {

// Add user info into the database table, claim your fields then values 
        $sql = mysql_query("INSERT INTO jobopening(name, email, phone,applieddate,Appliedjob) 
                VALUES('$_POST[name]','$_POST[email]','$_POST[phone]', now(),'dataentry')") or die (mysql_error());
        // Get the inserted ID here to use in the activation email
        $id = mysql_insert_id();

   $to = "example@example.co.in";

        // Change this to your site admin email


        $from = "$_POST[email]";

        $subject = "Applied for DataEntry FROM $_POST[name] ";

        //Begin HTML Email Message where you need to change the activation URL inside


// Get all the values from input
    $name = $_POST['name'];
    $email_address = $_POST['email'];
    $phone = $_POST['phone'];

 // Now Generate a random string to be used as the boundary marker
   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

   // Now Store the file information to a variables for easier access
   $tmp_name = $_FILES['filename']['tmp_name'];
   $type = $_FILES['filename']['type'];
   $file_name = $_FILES['filename']['name'];
   $size = $_FILES['filename']['size'];



   // Now here we setting up the message of the mail
   $message = "

   \n\n Applied For DataEntry
   \n\n Name: $name 
   \n\n Email: $email_address 
   \n\n Phone: $phone"; 


   // Check if the upload succeded, the file will exist
   if (file_exists($tmp_name)){

      // Check to make sure that it is an uploaded file and not a system file
      if(is_uploaded_file($tmp_name)){

         // Now Open the file for a binary read
         $file = fopen($tmp_name,'rb');

         // Now read the file content into a variable
         $data = fread($file,filesize($tmp_name));

         // close the file
         fclose($file);

         // Now we need to encode it and split it into acceptable length lines
         $data = chunk_split(base64_encode($data));
     }

      // Now we'll build the message headers
      $headers = "From: $from\r\n" .
         "MIME-Version: 1.0\r\n" .
         "Content-Type: multipart/mixed;\r\n" .
         " boundary=\"{$mime_boundary}\"";

      // Next, we'll build the message body note that we insert two dashes in front of the  MIME boundary when we use it
      $message = "This is a multi-part message in MIME format.\n\n" .
         "--{$mime_boundary}\n" .
         "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
         "Content-Transfer-Encoding: 7bit\n\n" .
         $message . "\n\n";

      // Now we'll insert a boundary to indicate we're starting the attachment we have to specify the content type, file name, and disposition as an attachment, then add the file content and set another boundary to indicate that the end of the file has been reached
      $message .= "--{$mime_boundary}\n" .
         "Content-Type: {$type};\n" .
         " name=\"{$file_name}\"\n" .
         //"Content-Disposition: attachment;\n" .
         //" filename=\"{$fileatt_name}\"\n" .
         "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n" .
         "--{$mime_boundary}--\n";


      // Thats all.. Now we need to send this mail... :)
      if (@mail($to, $subject, $message, $headers))
      {
         ?>
 <div><center><h1>Your Data Has been submitted we will contact you soon !!</h1></center></div>
    <?php
      }else
      {
         ?>
    <div>
      <center>
        <h1>Error !! Unable to send yor data..</h1>
      </center>
    </div>
    <?php
      }
   }
}
}
}
?>


 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
  <label>Name:</label>
  <input type="text" name="name"  value="<?php echo $_POST["name"]?>"/>
  <?php echo $nameErr?> <br />
  <br />
  <label>Email-ID:</label>
  <input type="text" name="email" value="<?php echo $_POST["email"]?>"/>
  <?php echo $emailErr?> <br />
  <br />
  <label>Phone No:</label>
  <input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/>
  <?php echo $phoneErr?> <br />
  <br />
  <label for="tele">upload Resume</label>
  <input type="file" name="filename" id="tele"/>
  <?php echo $uploadresumeErr?> <br />
  <br />
  <input style="display:block; margin-left:35em;"type="submit" value="Submit"/>
</form>

【问题讨论】:

  • 提交表单后为什么不尝试重新加载页面?
  • @Sulthan Allaudeen 提交表单后如何使用页面重新加载?
  • 在 if 条件下 - if(@mail) 使用 header('Location: example.com/');这是链接in2.php.net/manual/en/function.header.php
  • 如果他重新加载,需要编写单独的代码来显示成功消息

标签: php


【解决方案1】:

将$_POST存储在一个变量里面

 if(isset($_POST['name']))
 {
   $post_val=$_POST;
  ---------

然后,发送邮件后取消设置$post_val

  if (@mail($to, $subject, $message, $headers))
  {
   unset($post_val);
     ?>

显示来自$_post_val的值

  <input type="text" name="name"  value="<?php echo $_post_val["name"]?>"/>
  <input type="text" name="email" value="<?php echo $_post_val["email"]?>"/>   
  <input type="text" name="phone" value="<?php echo $_post_val["phone"]?>"/> 

【讨论】:

  • 他也可以使用指针或者原来的$_POST变量。原理是在我们使用成功后清除变量。
  • @Loenix,如何使用指针?我不知道如何?任何有用的链接?
  • 在 PHP 中,这是一个参考。例如 $post_val = &$_POST; .在这里, $post_val 和 $_POST 将始终具有相同的值,即使您分配了一个空值或 NULL 但使用 unset($post_val);引用将被删除。 (可能取决于 PHP 版本)
【解决方案2】:

您正在使用$_POST 变量设置字段的值。提交表单后,$_POST 数组将被填充。因此,在提交后加载页面时,会设置输入的值。您需要删除它们。

改变

 <input type="text" name="name"  value="<?php echo $_POST["name"]?>"/>
 <input type="text" name="email" value="<?php echo $_POST["email"]?>"/>   
 <input type="text" name="phone" value="<?php echo $_POST["phone"]?>"/>      

 <input type="text" name="name"  value=""/>
 <input type="text" name="email" value=""/>   
 <input type="text" name="phone" value=""/>      

【讨论】:

    【解决方案3】:

    将数据插入数据库并发送电子邮件后,您应该重定向到同一页面

    header("location:".$_SERVER['PHP_SELF']);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多