Reputation: 29
I am trying to build an application where users can insert data per day of a month. For that to happen I need to let the user create all days of a certain month (e.g.: current month).
With the click of a button I want it to get the current month and then use that data to get all days and make SQL Inserts for each month.
For example:
$monthname=date('F');
$monthnumber=date('m');
$getyear=date('Y');
Loop this until it has inserted all days of $monthnumber:
INSERT INTO $monthdatadays (id, dayname, daynumber, monthname, $monthnumber, year, data1, data2) VALUES ('', '$dayname', 'day1', '$monthname', '$monthnumber', '$getyear', '$somedata', '$somedata2')
INSERT INTO $monthdatadays (id, dayname, daynumber, monthname, $monthnumber, year, data1, data2) VALUES ('', '$dayname', 'day2', '$monthname', '$monthnumber', '$getyear', '$somedata', '$somedata2')
INSERT INTO $monthdatadays (id, dayname, daynumber, monthname, $monthnumber, year, data1, data2) VALUES ('', '$dayname', 'day3', '$monthname', '$monthnumber', '$getyear', '$somedata', '$somedata2')
Until the end of the month, but then months do have different amount of days.
How can I achieve this using prepared statements like this one:
if($exampleps= $mysqli->prepare("INSERT INTO $pstable(id, name, summary, full, closedopen, createdby, createdat, editedby, editedat, date, time)VALUES('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))
{
$exampleps -> bind_param("ssssssssss", $name, $summary, $full, $status, $createdby, $createdat, $editedby, $editedat, $date, $time);
$exampleps -> execute();
$exampleps -> close();
}
Upvotes: 2
Views: 1069
Reputation: 41885
You need to loop each day. You could use DatePeriod
. Example:
// setup dates
$begin = new DateTime();
$end = new DateTime();
$begin->modify('first day of this month');
$end->modify('last day of this month');
$interval = new DateInterval('P1D'); // 1 day interval
$range = new DatePeriod($begin, $interval, $end);
$mysqli = new mysqli('localhost', 'username', 'password', 'db');
$sql = "INSERT INTO $monthdatadays (id, dayname, daynumber, monthname, $monthnumber, year, data1, data2) VALUES ('', ?, ?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
foreach($range as $k => $date) {
$somedata = 'whatever';
$somedata2 = 'whatever';
$dayname = $date->format('l');
$day = 'day' . $date->format('j');
$monthname = $date->format('F');
$monthnumber = $date->format('n');
$year = $date->format('Y');
$stmt->bind_param('sssssss', $dayname, $day, $monthname, $monthnumber, $year, $somedata, $somedata2);
$stmt->execute();
}
Upvotes: 1
Reputation: 2525
You Can use MySQL NOW() function Return the current date and time.
E.g.
mysqli_query("INSERT INTO users (first, last, date_time) VALUES ('$first', '$last', now())");
You can apply
$mysqli->prepare("INSERT INTO $pstable(id, name, summary, full, closedopen, createdby, createdat, editedby, editedat, date, time) VALUES('', ?, ?, ?, ?, ?, now(), ?, now(), CURDATE(),CURTIME())");
Upvotes: 0