Bahij.Mik
Bahij.Mik

Reputation: 1484

PHP - Convert separate day, month, and year to mysql date format

I have a day value (1-31), a month value (1-12), and a year value, and i need to save them in my MySQL database date format.

How can i convert those values (3 integers corresponding to the day, month, and year) to a date format to save it in my database?

$day = $request->day;     // day(1-31)
$month = $request->month; // month(1-12)
$year = $request->year;  // year

$date = strtotime("$year-$month-$day"); // how to convert above values to a MySQL **date** format?

Upvotes: 0

Views: 304

Answers (1)

Dharman
Dharman

Reputation: 33238

You could simply concatenate the three values together if you are 100% sure of the values.

$mysqlDate = $request->year.'-'.$request->month.'-'.$request->day;

You can use DateTime class to validate that the integers make a valid date. For example with this code:

$mysqlDate = (new \DateTime())->setDate($request->year, $request->month, $request->day)->format('Y-m-d');

This will make sure that the date is a proper date and will not cause MySQL errors when you try to enter it into the database.

Then you can simply use this in your prepared statement like this:

$pdo->prepare('INSERT INTO someTable(someDateColumn) VALUES(?)')
    ->execute([$mysqlDate]);

Upvotes: 1

Related Questions