如何防止PHP脚本表单更改为另一个页面

时间:2014-02-02 01:01:59

标签: php html forms

我使用了一个我在这里找到一个调用PHP脚本的HTML页面的示例,两者都列在下面。 这一切都运行良好 - 但是,我最终得到PHP脚本页面,我想避免它 - 我想留在HTML页面,而不是移动到任何地方。我在某些地方读过我需要JS或AJAX,但看不到任何实际的例子。

我正在使用安装了IIS 7.5版的Windows 7下的PC上工作,PHP 5.3.28。 并在c:\ inetpub.wwwroot

中执行HTML文件

HTML

<div id="contact">
   <h2>Enter your First and Last Name</h2>

   <form action="frm_script.php" method="post" target="_parent">
   <p><strong>First Name:</strong><br /> <input type="text" name="firstName" /></p>
   <p><strong>Last Name:</strong><br /> <input type="text" name="lastName"/></p>
   <input type="submit" name="submit" value="Add Customer" />
   </form>

</div>

PHP脚本

<?php
if(isset($_POST['submit']))
{
    //get the name and comment entered by user
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];

    //connect to the database
    $dbc = mysqli_connect('localhost', 'root', 'root', 'mdpdata') or die('Error connecting to 
    MySQL server');
    $check=mysqli_query($dbc,"select * from clients where firstname='$firstname' and 
    lastname='$lastname'");
    $checkrows=mysqli_num_rows($check);
    if($checkrows>0)
    {
  print "customer exists";      
    }  
    else
    {  
        //insert results from the form input
        $query = "INSERT INTO clients(firstName, lastName) VALUES('$firstName', '$lastName')";
        $result = mysqli_query($dbc, $query) or die("Sorry, Duplicate Record.'$php_errormsg'");
        mysqli_close($dbc);
    }
    print '<script type="text/javascript">'; 
    print 'alert("The Customer is NOW registered")'; 
    print '</script>';  

};
?>

1 个答案:

答案 0 :(得分:1)

包含带有action =“”语句的表单的html文档会导致更改为指定的页面。和你的一样,到frm_script.php

如果您不希望发生这种情况,您需要一个AJAX请求,如上所述,或者您可以添加

header(location: 'FPRM.HTML');

到php脚本的底部。因此,处理后应该非常快,再次加载原始页面。

或者你根本不使用两页。在PHP代码之后,只需将FPRM.HTML中的html代码放到底部,这样一旦表单值保存,页面就会被重新加载。在这种情况下,只需将FPRM.php调用连接文档,并且必须将表单操作设置为action =“FPRM.php”,或者根本不需要,因为无操作语句的表单无论如何都会加载相同的页面。