【问题标题】:Value from checkbox send by mail - PHP form来自通过邮件发送的复选框的值 - PHP 表单
【发布时间】:2016-12-21 20:27:18
【问题描述】:

我的后端有这个 PHP 代码

if(!empty($_POST['model_list'])) {
            foreach($_POST['model_list'] as $model) {
            }
        } else {
            throw new Exception('Choose the model.');
        }

当我收到来自前端的请求时,$_POST['model_list'] 变量似乎不包含前端指定的值。

这是我的 HTML 代码:

<input type="checkbox" value="A" name="model_list[]"><span>A</span>

我有一个错误:

注意:未定义变量:/form.php 第 17 行中的模型

第 17 行:

$body = "Name: $name \n E-mail: $email \n Phone number: $tel \n Serial number: $number \n Model: $model \n Message: $message \n";

完整代码:

<?php
if (isset($_POST["submit"])) {
    $name       = (string) $_POST['name'];
    $email      = (string) $_POST['email'];
    $message    = (string) $_POST['message'];
    $number     = (string) $_POST['number'];
    $tel        = (string) $_POST['tel'];
    $from       = 'name@domain.tld';
    $to         = 'name@domain.tld';
    $subject    = 'Form';

    $body = "Name: $name \n E-mail: $email \n Phone number: $tel \n Serial number: $number \n Model: $model \n Message: $message \n";

    try {
        if (!$name) {
            throw new Exception('Write name.');
        }
        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new Exception('Write correct e-mail');
        }
        if (!$message) {
            throw new Exception('Write message');
        }
        if (mail ($to, $subject, $body, $from)) {
            $result = "<center><div style='color:white;font-size:15px;font-weight:700;'>Your message has been sent</div></center>";
        } else {
            throw new Exception("Your message has not been sent, try again");
        }
        if(!empty($_POST['model_list'])) {
            foreach($_POST['model_list'] as $model) {
            }
        } else {
            throw new Exception('Choose the model.');
        }
    } catch(Exception $e){
        $result = "<center><div style='color:white;font-size:25px;font-weight:700;'>" . $e->getMessage() . "</div></center>";
    }

    echo $result;
}
?>

提前致谢。

【问题讨论】:

  • 好吧,我编辑了psot
  • 在分配给$body之前,您不会设置$model
  • 当我添加 '$model = (string) $_POST['model_list']' 时,我收到了一封电子邮件,其中“array”为模型
  • 实际上,您在发送邮件之前不会设置$model
  • 邮件中应该包含什么内容?既然是数组,或许你应该使用$model = implode(',', $_POST['model_list']);

标签: php forms checkbox


【解决方案1】:

要获取电子邮件中的所有模型,请使用implode

if (!empty($_POST['model_list'])) {
    $model = implode(', ', $_POST['model_list']);
} else {
    $model = '';
}

【讨论】:

    猜你喜欢
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多