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

OpenCart订单分配邮件异常问题排查与代码修复请求

问题分析与修复方案

原代码核心问题

  • SQL查询字段缺失:仅查询preluat字段,但后续调用了order_id、firstname等字段,会导致变量未定义,引发逻辑异常。
  • 类型不匹配导致switch失效:数据库preluat字段为整数类型,代码中用字符串'4'、'5'作为case值,类型不匹配时switch不会进入对应分支,$to_email未被正确赋值,若此前存在默认值则会一直发送给第一个员工。
  • 变量未初始化:若preluat值非4/5,$to_email会处于未定义状态,触发语法警告。
  • 无效注释符号:代码末尾的*/属于未闭合注释,可能干扰代码执行。

修复后的完整代码

// 修正SQL查询,获取所有需要的订单字段
$order_query = $this->db->query("SELECT preluat, order_id, firstname, lastname, total, store_name FROM " . DB_PREFIX . "order WHERE order_id = '" . (int)$order_id . "'");
$order = $order_query->row;

if ($order) {
    $lady1_email = "email1@name.com";
    $lady2_email = "email2@name.com";
    // 初始化变量,避免未定义问题
    $to_email = '';

    // 强制转为整数匹配case,对应数据库字段类型
    switch ((int)$order['preluat']) {
        case 4:
            $to_email = $lady1_email;
            break;
        case 5:
            $to_email = $lady2_email;
            break;
        // 可选:添加默认分支处理异常值
        default:
            // 可设置默认收件人或记录日志
            // $to_email = 'admin@example.com';
            break;
    }

    if ($to_email != "") {
        $subject = "New order received";
        $body = "Dear Lady,\n\nA new order has been allocated to you. Please check your order list and start processing it as soon as possible.\n\nOrder details:\nOrder ID: " . $order['order_id'] . "\nCustomer Name: " . $order['firstname'] . " " . $order['lastname'] . "\nOrder Total: " . $order['total'] . "\n\nBest regards,\nYour Employer";

        $mail = new Mail();
        $mail->protocol = $this->config->get('config_mail_protocol');
        $mail->parameter = $this->config->get('config_mail_parameter');
        $mail->hostname = $this->config->get('config_smtp_host');
        $mail->username = $this->config->get('config_smtp_username');
        $mail->password = $this->config->get('config_smtp_password');
        $mail->port = $this->config->get('config_smtp_port');
        $mail->timeout = $this->config->get('config_smtp_timeout');
        $mail->setTo($to_email);
        $mail->setFrom($this->config->get('config_email'));
        $mail->setSender($order['store_name']);
        $mail->setSubject($subject);
        $mail->setText($body);
        $mail->send();
    }
}

关键修复说明

  1. 补充查询字段:确保后续用到的order_id、firstname等字段都被查询,避免未定义错误。
  2. 统一类型匹配:将$order['preluat']强制转为整数,匹配数据库字段类型,保证switch分支正确触发。
  3. 初始化变量:提前定义$to_email为空字符串,避免未定义变量引发的问题。
  4. 移除无效注释:删除末尾的*/,确保代码正常解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:20