如何使用 HTML 表单将日期时间正确插入 MYSQL 数据库?

How to correctly insert datetime into MYSQL database using HTML form?

我遇到了一个看似相对简单的问题,但它造成的问题比我想象的要多。您可能知道,HTML5 不再支持表单字段的 "datetime" 输入,而仅支持 "datetime-local"。当我尝试通过我网站上的表单将 "datetime-local" 插入我的数据库时,由于 "datetime-local" 中包含的额外字符,我显然会收到错误消息。我想要做的,以及为什么我需要一个日期时间字段而不是在各自字段中只需要一个日期 and/or 时间,是因为我想使用 Carbon 以不同的格式显示我的日期时间。如何通过 HTML 形式将日期时间插入 mysql table 而无需手动将值插入我的数据库?

编辑: 这是我试图用它来实现的所有相关代码。我正在使用 Laravel 构建此应用程序

game/create形式:

<select name="season_id">

        @foreach ($seasons as $season)

        <option name="season_id" value="{{ $season->id }}">{{ $season->season }} {{ $season->year }}</option>

        @endforeach

</select>

<label for="inputDateTime" class="sr-only">DateTime</label>
    <input type="datetime-local" name="gdatetime" id="inputDateTime" class="form-control" placeholder="DateTime" required autofocus>

<label for="inputOpponent" class="sr-only">Opponent</label>
    <input type="text" name="opponent" id="inputOpponent" class="form-control" placeholder="Opponent" required autofocus>

<label for="inputLocation" class="sr-only">Location</label>
    <input type="text" name="location" id="inputLocation" class="form-control" placeholder="Location" required autofocus>

<label for="inputField" class="sr-only">Field</label>
    <input type="text" name="field" id="inputField" class="form-control" placeholder="Field" required autofocus>

游戏控制器:

$game = Game::create(request(['gdatetime', 'opponent', 'location', 'field', 'season_id']));

此外,在我的 Game 模型中,我定义了这个:

protected $dates = ['gdatetime'];

使用PHP进行转换。

date('date format here', strtotime($user_input);

date()

strtotime()

并且始终确保在服务器端验证用户输入,否则 strtotime() 可能 return 错误导致 date() 到 return 1969。

您始终可以将日期时间输入解析为碳实例并将它们存储在数据库中。解析将处理存储前格式化输入带来的麻烦。然后,您可以在需要时以任何格式显示它们。

$date = \Carbon\Carbon::parse($request->input('datetime'));

编辑:根据您的评论和更新,执行此操作。

$data = request(['opponent', 'location', 'field', 'season_id']);

$data['gdatetime'] = \Carbon\Carbon::parse(request('gdatetime'));

$game = Game::create($data);

或者您可以在模型文件中定义:

protected $dates = ['your_date_field];

当您从数据库中获取它时,它将是一个 Carbon 实例。