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

PHP表单数据插入PHPMailer邮件体仅显示最后一条数据问题求助

问题分析与修复方案

核心错误原因

  1. 数据收集逻辑错误:第一个循环中,你每次将$quantitad_form赋值为单条数据,而非将所有数据存入数组。循环结束后,$quantitad_form只会保留最后一条记录,而非完整的数据集。
  2. 邮件体构建错误:第二个循环中,你直接用$mail->Body = $value替换邮件内容,每一次循环都会覆盖之前的内容,最终仅保留最后一条数据。

修正后的完整代码

第一步:正确收集所有表单数据

// 初始化数组存储所有表单详情
$formData = [];
// 获取固定字段(非数组类型的字段)
$referente = $_POST["referente"];
$email = $_POST["email"];

// 遍历数组字段,收集所有数据
$totalItems = count($_POST["quantitad_form"]);
for ($i = 0; $i < $totalItems; $i++) {
    $formData[] = [
        'id_form' => $_POST["id_form"][$i],
        'quantitad_form' => $_POST["quantitad_form"][$i],
        'quantitae_form' => $_POST["quantitae_form"][$i],
        // 根据实际表单字段添加dataplate、energy label
        'dataplate' => $_POST["dataplate"][$i],
        'energy_label' => $_POST["energy_label"][$i]
    ];
}

第二步:正确构建PHPMailer邮件体

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);
try {
    // Server settings(保持你的原有配置)
    $mail->SMTPDebug = 2;
    $mail->isSMTP();
    $mail->Host = 'mysmtp';
    $mail->SMTPAuth = true;
    $mail->Username = 'myemail';
    $mail->Password = 'mypassword';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('emailfrom');
    $mail->addAddress($email); // 使用之前收集的email变量

    // Content
    $mail->isHTML(true);
    $mail->Subject = '表单提交信息';
    
    // 初始化邮件体,添加固定信息
    $mail->Body = "<h3>提交人基本信息</h3>
    <p>Referente: {$referente}</p>
    <p>Email: {$email}</p>
    <h3>表单明细</h3>
    <ul>";

    // 遍历收集到的所有数据,追加到邮件体
    foreach ($formData as $item) {
        $mail->Body .= "<li>
            <strong>ID:</strong> {$item['id_form']}<br>
            <strong>Quantitad:</strong> {$item['quantitad_form']}<br>
            <strong>Quantitae:</strong> {$item['quantitae_form']}<br>
            <strong>Dataplate:</strong> {$item['dataplate']}<br>
            <strong>Energy Label:</strong> {$item['energy_label']}
        </li>";
    }

    // 闭合HTML标签
    $mail->Body .= "</ul>";

    $mail->send();
    header('Location: http://www.example.net/contact.php');
    exit();
} catch (Exception $e) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}

关键说明

  • 用数组$formData统一存储所有表单明细,避免单个变量被覆盖。
  • 构建邮件体时使用.=运算符追加内容,而非直接赋值=,确保所有数据都能保留在邮件中。
  • 添加HTML标签(如<h3>、<ul>、<li>)让邮件内容结构清晰,可读性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:35:13