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

如何通过HTML输入框提交数字实现PHP批量插入指定条数随机姓名数据至数据库?

批量插入随机姓名数据功能实现

我已经开发完成了一个功能:用户在首页输入数字后,程序会从专用数据表中随机选取对应数量的姓名数据,并插入到目标数据表中。比如输入5,就会插入5条随机生成的姓名记录,目前这个功能已经可以正常运行,具体实现如下:

功能逻辑说明

  • 在首页提供仅支持数字输入的输入框,要求输入值大于0
  • 用户提交后,后端接收输入的数字,循环对应次数
  • 每次循环从data表中随机获取一条姓名(名+姓)
  • 将获取到的姓名插入到students目标数据表
  • 操作完成后自动跳转回首页

1. 后端处理文件(inc/input.php)

这个文件负责处理用户的提交请求,完成随机姓名查询和插入操作:

<?php 
include "connection.php"; 

// 校验输入有效性:非空且大于0
if (!empty($_POST["input"]) && 0 < $_POST["input"]) { 
    $input_value = intval($_POST["input"]); 

    // 循环生成指定数量的记录
    for ($i = 0; $i < $input_value; $i++) { 
        // 从data表随机查询一条姓名数据
        $get_names_stmt = $mysqli->prepare("SELECT data_firstname, data_lastname FROM data ORDER BY RAND(?) LIMIT 1");
        $get_names_stmt->bind_param('i', $input_value); // 绑定整数参数,避免SQL注入
        $get_names_stmt->execute();
        $get_names_stmt->bind_result($firstname, $lastname); // 绑定查询结果到变量
        $get_names_stmt->store_result();

        // 准备插入students表的预处理语句
        $insert_names_stmt = $mysqli->prepare("INSERT INTO students (student_firstname, student_lastname) VALUES (?, ?)");
        $insert_names_stmt->bind_param("ss", $firstname, $lastname); // 绑定两个字符串类型参数

        // 执行插入操作
        while ($get_names_stmt->fetch()) {
            $insert_names_stmt->execute();
        }
    }
}

// 跳转回首页
header("Location:../index.php");
?>

2. 前端首页文件(index.php)

首页包含两个表单:一个用于重置清空目标表,另一个用于输入要生成的记录数量:

<?php 
include "inc/connection.php"; 
include "inc/truncate.php"; 
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Content Generator</title>
</head>
<body>
    <!-- 清空students表的Reset按钮 -->
    <form action="inc/truncate.php" method="post">
        <button type="submit" name="truncate">Reset</button>
    </form>

    <!-- 输入记录数量并提交的表单 -->
    <form action="inc/input.php" method="post">
        <input type="number" name="input" min="0" required>
        <button type="submit" name="submit">Send</button>
    </form>
</body>
</html>

补充说明:

  • 这里使用预处理语句来执行数据库操作,有效避免了SQL注入风险
  • RAND(?)中的参数是为了满足预处理的绑定要求,确保查询的随机性
  • truncate.php文件负责实现清空students表的逻辑,需要自行补充对应的代码(比如执行TRUNCATE TABLE students;语句)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:02:30