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

PHP多条件验证后如何传递并显示多条错误信息?

解决多错误信息传递问题

你当前的问题在于用数字累加的方式传递错误码,当多个错误同时触发时,累加后的数值会和单个错误码混淆(比如1+2=3,会被误认为是第三个错误),导致无法正确显示所有触发的错误。以下是两种适合新手的解决方案:

方案1:使用JSON传递错误数组

这种方式清晰直观,便于扩展更多错误类型。

修改doAddOrder.php

$errors = [];

// 验证所有条件,收集错误标识
if ($origin == $destination) {
    $errors[] = 'origin_dest_same';
}

if ($stuffing_date > $dep_date) {
    $errors[] = 'stuffing_after_dep';
}

if ($dep_date > $arr_date) {
    $errors[] = 'dep_after_arr';
}

// 存在错误时跳转并传递错误信息
if (!empty($errors)) {
    // 转成URL安全的JSON字符串
    $errorStr = urlencode(json_encode($errors));
    header("Location: admin-add-order.php?errors=$errorStr");
    exit;
}

修改admin-add-order.php

<?php 
if (isset($_GET["errors"])) {
    // 解析传递来的错误数组
    $errors = json_decode(urldecode($_GET["errors"]), true);
    // 定义错误标识对应的消息
    $errorMessages = [
        'origin_dest_same' => 'Origin and destination must be different',
        'stuffing_after_dep' => 'Departure date cannot be earlier than stuffing date',
        'dep_after_arr' => 'Arrival date cannot be earlier than departure date'
    ];
    // 遍历显示所有错误
    foreach ($errors as $errorKey) {
        if (isset($errorMessages[$errorKey])) {
            echo $errorMessages[$errorKey] . '<br>';
        }
    }
} 
?>

方案2:使用逗号分隔错误码

如果觉得JSON复杂,可以用简单的字符串拼接传递错误码。

修改doAddOrder.php

$errorCodes = [];

// 收集触发的错误码
if ($origin == $destination) {
    $errorCodes[] = 1;
}

if ($stuffing_date > $dep_date) {
    $errorCodes[] = 2;
}

if ($dep_date > $arr_date) {
    $errorCodes[] = 3;
}

// 存在错误时跳转
if (!empty($errorCodes)) {
    $errorStr = implode(',', $errorCodes);
    header("Location: admin-add-order.php?errors=$errorStr");
    exit;
}

修改admin-add-order.php

<?php 
if (isset($_GET["errors"])) {
    // 拆分错误码
    $errorCodes = explode(',', $_GET["errors"]);
    // 遍历显示对应错误
    foreach ($errorCodes as $code) {
        switch ($code) {
            case 1:
                echo "Origin and destination must be different<br>";
                break;
            case 2:
                echo "Departure date cannot be earlier than stuffing date<br>";
                break;
            case 3:
                echo "Arrival date cannot be earlier than departure date<br>";
                break;
        }
    }
} 
?>

两种方案都会先遍历所有验证条件,收集所有触发的错误,再一次性传递到目标页面并显示全部错误信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:25:22