0

I need to insert into MySQL as January 2021 - April 2021 using the form as shown in the image. But when I save it is inserted into MySQL as 2021-01 - 2021-04. How to save input type=month as month name? I have searched for the solutions but the solutions did not fit my need.

enter image description here

<th class="td-info">Semester semasa:</th>
<td>
    <input type="month" name="startSem" required> - <input type="month" name="finishSem" required>
    <p style="color: gray">eg: Januari 2020 - Mei 2021</p>
</td>

In PHP I create a new variable to combine two input type=month

$currentSem = $_POST['startSem'] . " - " . $_POST['finishSem'];

In MySQL, I use varchar instead of DATE

enter image description here

Mhd Alaa Alhaj
  • 2,438
  • 1
  • 11
  • 18
  • 3
    Don't. use DATE types and store values 2021-01-01 for that month. Use your PHP to format the date however you want when you use it. The structured form allows SQL to use this efficiently. – danblack Jan 13 '21 at 05:48
  • Is the purpose of saving the month _name_ for localization? By default, PHP saves month as numbers because that's the most raw format you can have a month in (and it's the most efficient in MySQL in that format). If you specifically need the name of the month, I suggest you use https://stackoverflow.com/questions/3768072/php-date-function-to-get-month-of-the-current-date before saving. Or better yet, save in the default format (numbers), but on output back to the user you can use `date()` to get the name again. – WOUNDEDStevenJones Jan 13 '21 at 05:50
  • this [comment of @David Storey](https://stackoverflow.com/a/18648314/8134014) could help you – Burham B. Soliman Jan 13 '21 at 05:54
  • Thank you for all the answer but some of the answers get me confused as I'm new to PHP. I will study all the answers provided – Jekyll Hyde Jan 13 '21 at 06:05

2 Answers2

1

use this as example

$date = $your_variable_for_date;
echo date('F Y', strtotime($date));

see this as reference: enter image description here

Ainz
  • 366
  • 2
  • 13
0

Use below code to format the date and combine both dates and save $combineDate variable in database.

$startSem = $_POST['startSem'];
$finishSem = $_POST['finishSem'];
$changeDateFormatStartSem = date('F Y', strtotime($_POST['startSem']));
$changeDateFormatfinishSem = date('F Y', strtotime($_POST['finishSem']));
echo $combineDate = $changeDateFormatStartSem." - ".$changeDateFormatfinishSem;  //output January 2021 - April 2021
Talk2Nit
  • 1,115
  • 3
  • 22
  • 38