You need to enable JavaScript to run this app. PHP如何将当日日期与用户输入时间拼接为可入库的datetime值
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何将当日日期与用户输入时间拼接为可入库的datetime值

代码修复方案

触发运行报错的核心原因

  • $date_jour = Date('Y-m-d') 返回纯字符串,不是 DateTime 实例,对字符串调用 ->format() 方法会直接触发类型错误
  • 表单 <input type="time"> 提交的是纯字符串格式的时间值,传入方法的 $date_commencement_journee 是字符串类型,不是 DateTime 对象,调用 ->format() 同样会触发类型错误

附带的隐藏代码问题

  • 预编译SQL语句中 INSERT INTO activiteVALUES 缺少空格,会触发SQL语法错误
  • 参数绑定时使用了未定义的 $ID 变量,实际定义的车辆ID变量是 $identifiant_camion,会触发变量未定义警告
  • DateTime 对象无法直接用于SQL参数绑定,直接绑定会被序列化为不可识别的Object字符串,无法匹配数据库datetime字段格式

修正后的可运行代码

function insertionHeureDebutJournee($date_commencement_journee)
{
    if ($this->estPremiereConnexion()){
        $identifiant_camion = $this->GetID();
        // 正确创建当日DateTime实例
        $date_jour = new DateTime('today');
        // 拼接完整的datetime字符串,兼容time输入框提交的HH:MM/HH:MM:SS格式
        $date_merge_str = $date_jour->format('Y-m-d') . ' ' . $date_commencement_journee;
        // 生成可用于校验的DateTime对象
        $date_merge = new DateTime($date_merge_str);
        
        $connexion = $this->GetConnexion();
        // 修正表名与VALUES关键字之间的空格
        $stmt = $connexion->prepare("INSERT INTO activite VALUES (0, ?, ?)");
        // 修正未定义的变量名,绑定参数时转为数据库要求的标准datetime格式字符串
        $stmt->bind_param('ss', $identifiant_camion, $date_merge->format('Y-m-d H:i:s'));
        
        if($stmt->execute() === false){
            echo 'Problème dans l\'insertion de la date et l\'heure de début de journée';
        }else{
            header('Location: ../index.php');
            exit; // 跳转后终止后续代码执行
        }
    }
}

适配说明:<input type="time">提交的时间值格式为HH:MM或HH:MM:SS,与当日Y-m-d格式拼接后可被DateTime正常解析,生成的Y-m-d H:i:s格式字符串完全适配主流数据库的datetime字段存储要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.28 07:24:03