user3092953 user3092953 - 1 month ago 12
MySQL Question

Add all dates from current month to DB table

I am wanting to add all dates within the current month to a database table

I just need the full date

Y-m-d
, month number (E.g.
10
) and year (E.g.
2016
)

Any ideas if this is possible and how I could do this?

Answer

The date function has the following feature:

http://php.net/manual/en/function.date.php

t, Number of days in the given month, 28 through 31

You can create a loop to do the insert you want:

<?php

$totalDays = date('t'); // total days for current month
$currentMonth = date('m');
$currentYear = date('Y');

for ($x=1; $x<=$totalDays; $x++) {
    $x = sprintf('%02d', $x);;
    $date = "$currentYear-$currentMonth-$x";

    // Do something with your $date variable here
}

For a specific month, you can use either mktime (http://php.net/mktime):

$totalDays = date('t', mktime(0, 0, 0, 10, 1, 2016)); // Total days for Oct 2016

Or, use cal_days_in_month (http://php.net/cal_days_in_month)

$totalDays = cal_days_in_month(CAL_GREGORIAN, 10, 2016); // Total days for Oct 2016