如何在不实际打开php文件并显示空白页面的情况下执行插入查询?

时间:2013-09-08 17:36:15

标签: php html

我有一个主窗体,其中有一个提交按钮,按下它时会使用插入查询插入员工数据,但是当我按下窗体中的提交按钮时,它会打开一个空白页面,因为结果窗体中没有可见内容。我如何得到它,以便当我按下提交按钮时,它只输入数据,但保持在同一表格上,不打开空白页面。这甚至可能吗?我是否必须简单地将index.php的样式复制到process.php文件中?请帮助我是新手,想要学习。

这是我的代码(index.php)

<html>
<head>

</head>
<body>


    <form action="process.php" method="post" style="position:relative; top:200px;left:150px">
        First Name: <input type="text" style="position:relative;left:14px"name="firstName"><br>
        Last Name: <input type="text" style="position:relative;left:15px"name="lastName"><br>

        <input type="submit"style="position:relative;left:88px"name="submitButton"  ><br>


    </form>
</body>
</html>

这是执行查询的结果php文件(process.php)

<html>
<body>


  <?php
    $myServer = "MyComputerName\SQLEXPRESS";
    $myUser = "Username";
    $myPass = "password";
    $myDB = "Northwind"; 

    //connection to the database
    $dbhandle = mssql_connect($myServer, $myUser, $myPass)
      or die("Couldn't connect to SQL Server on $myServer"); 

    //select a database to work with
    $selected = mssql_select_db($myDB, $dbhandle)
      or die("Couldn't open database $myDB"); 

    $query = "Insert into Employees values ('".$_POST["firstName"]."','".$_POST["lastName"]."')";

      mssql_query($query);

      mssql_close();

    ?>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

是的,这是可能的。

<强> 1。 AJAX

正如tymeJV在评论中已经提到的那样:你可以使用AJAX。

<强> 2。改变process.php

第二个选项是更改 process.php -file。

<?php
$myServer = "MyComputerName\SQLEXPRESS";
$myUser = "Username";
$myPass = "password";
$myDB = "Northwind"; 

//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer"); 

//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
  or die("Couldn't open database $myDB"); 

$query = "Insert into Employees values ('".$_POST["firstName"]."','".$_POST["lastName"]."')";

  mssql_query($query);

  mssql_close();

  // Redirect
  header("location: index.php");
?>

丢失HTML标记并添加重定向标头。您确实需要删除HTML,因为如果已经有输出,则无法发送标题...

为什么这样做?

在任何输出之前,标题会被发送到客户端的浏览器,因此在用户在屏幕上看到任何内容之前,他会被重定向到index.php页面。