Tuesday, May 23, 2017

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

I have what seems to be a relatively simple issue that has caused more problems than I thought it would. As you probably know, HTML5 no longer supports the "datetime" input for a form field, and only supports "datetime-local". When I try to insert "datetime-local" into my database through a form on my website, I obviously get an error because of the extra character included in "datetime-local". What I am trying to do, and why I need a datetime field as opposed to just a date and/or time in their own respective fields is because I want to use Carbon to display my datetime in different formats. How can I insert datetime through HTML form into mysql table without manually inserting the value into my database?

EDIT: Here is all of the relevant code that I am trying to achieve this with. I am using Laravel to build this application

game/create form:

<select name="season_id">

        @foreach ($seasons as $season)

        <option name="season_id" value=""> </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 controller:

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

Also, in my Game model, I have defined this:

protected $dates = ['gdatetime'];



via hoolakoola

Advertisement