You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何index.php无显式调用代码却能触发同一文件夹的insert.php?

问题

我下载了两个PHP文件,一个是用于输入表单的index.php,另一个是insert.php,已将它们放置在同一文件夹中。点击提交按钮后,insert.php会正常执行并将表单数据插入我的数据库,但我有一个疑问:insert.php是如何被调用的?因为index.php中没有显式调用insert.php的代码。

index.php 代码

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>GFG- Store Data</title>
   </head>
   <body>
      <center>
         <h1>Storing Form data in Database</h1>
         <form action="insert.php" method="post">          
<p>
               <label for="firstName">Name:</label>
               <input type="text" name="name" id="name">
            </p>             
<p>
               <label for="lastName">Branch:</label>
               <input type="text" name="branch" id="branch">
            </p>             
<p>
               <label for="Gender">Roll Number:</label>
               <input type="text" name="roll_no" id="roll_no">
            </p>
  
            <input type="submit" value="Submit">
         </form>
      </center>
   </body>
</html>

insert.php 代码

<!DOCTYPE html>
<html>
 
<head>
    <title>TEST</title>
</head>
 
<body>
    <center>
        <?php
 
        $conn = mysqli_connect("localhost", "root", "", "test");
         
        // Check connection
        if($conn === false){
            die("ERROR: Could not connect. "
                . mysqli_connect_error());
        }
         
        // Taking all 3 values from the form data(input)
        $name =  $_REQUEST['name'];
        $branch = $_REQUEST['branch'];
        $roll_no =  $_REQUEST['roll_no'];
                 
        // Performing insert query execution
        // here our table name is college
        $sql = "INSERT INTO student  VALUES ('$name','$branch','$roll_no')";
         
        if(mysqli_query($conn, $sql)){
            echo "<h3>data stored in a database successfully."
                . " Please browse your localhost php my admin"
                . " to view the updated data</h3>";
          } 
        else{
            echo "ERROR: Hush! Sorry $sql. "
                . mysqli_error($conn);
        }
         
        // Close connection
        mysqli_close($conn);
        ?>
    </center>
</body>
 
</html>
解答

insert.php是通过HTML表单的action属性被调用的,你可以在index.php的<form>标签里看到这段核心配置:

<form action="insert.php" method="post">

点击「Submit」按钮时,浏览器会按以下流程触发insert.php的执行:

  1. 收集表单中所有带name属性的输入字段数据
  2. 按照method="post"指定的HTTP方法,将数据打包发送到action属性指向的文件——同目录下的insert.php
  3. 服务器接收到请求后,执行insert.php内的PHP代码,完成数据库连接、数据插入等操作
  4. 最后将insert.php的执行结果返回给浏览器展示

这是HTML表单的原生机制,不需要在index.php中编写显式调用的PHP代码。

另外需要注意:当前insert.php存在SQL注入风险,建议使用预处理语句(如mysqli的prepare方法)替代直接拼接SQL字符串,避免安全漏洞。


内容的提问来源于stack exchange,提问作者musab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:36:18