-2

I have a textbox on one of my forms, the user enters a date in the form of dd/mm/yy but when i try to insert it into one of my tables in my database, it enters it as 0000-00-00. how can I fix this? I want it to show on this format on my database dd/mm/yy

this is my following insert where $start is the data variable

  $query = "INSERT INTO paycheck (payCheckId,jobId,payRate,jobLocation,hoursWorked,startPeriod,empId)
  VALUES('','$job_id','$pay_rate','$job_location','$hours','$start','$userId')";
  $result = mysqli_query($db, $query); //we make the query
Israel Gonzales
  • 19
  • 1
  • 2
  • 7

2 Answers2

1

You can chose either MySQL to do this, or you can have PHP do it for you.

For MySQL related solution, please check STR_TO_DATE() function and for PHP the function date() does it.

Usage in STR_TO_DATE() is:

STR_TO_DATE( '$startPeriod', '%d/%m/%Y' )

Hence, the query will be:

INSERT INTO paycheck (payCheckId, jobId, payRate, 
    jobLocation, hoursWorked, startPeriod, empId)
VALUES( '', '$job_id', '$pay_rate',
    '$job_location', '$hours', 
    STR_TO_DATE( '$startPeriod', '%d/%m/%Y' ), '$userId')
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0

You need to reformat your date so MySQL can read it. The format the database saves to is yyyy-mm-dd. If you would like to display the date in the format it originally came in, simply use the date() function like so: $date = date("d/m/y", strtotime($dateFromDB));

This might be a long winded way of doing it, and there are better ways out there however, you can create your own function to reformat it:

function reformatDate($incorrectFormat) {

  list($d, $m, $y) = explode("/", $input);
  $todaysYearBeginning = substr(0, 2, date("Y", time()));


  if(strlen($d == 1) {
    $d = "0" . $d;
  }
  if(strlen($m == 1) {
    $m = "0" . $m;
  }
  if(strlen($y == 1) {
    $y = "0" . $y;
  }

  return $todaysYearBeginning . $y . "-" . $m . "-" . $d;

}

echo reformatDate("dd/mm/yy");

Following on from Dream Eater's answer, you can use DateTime::CreateFromFormat like so:

$oldDate = DateTime::createFromFormat('d/m/y', $dateFromDB);
$newDate = $oldDate->format('Y-m-d');
Oliver Tappin
  • 2,511
  • 1
  • 24
  • 43