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


How to execute insert query without actually opening the php file and showing a blank page?

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

这是我的代码(索引.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 文件(进程.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. 阿贾克斯

正如tymeJV在他的评论中已经提到的:你可以使用AJAX来实现这一点。

2.变更流程.php

第二种选择是更改进程.php文件。

<?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,因为如果已经有输出,则无法发送标头...

为什么会这样?

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