skip to Main Content

I want to save only year in my database as date_created with type currenttimestamp

I’m getting the value of the year from a select html.
After getting the value, i will transfer it to the controller

Here’s my code

$registered_year = sanitize($this->input->post('registered_year'));
$registered_year2 =". $registered_year .-00-00 00:00:00";
$app_type = 1;
$ref_no = generate_reference_number();

$this->Model->dealer_renew_save($account_id,$req_id,$ref_no,$app_type,$registered_year2);

$data = [
         'success'=>1,
         'message'=> 'Application Successfully Renewed.'
         ];

generate_json($data);

For example, I chose 2018 then I want it to save 2018-00-00 00:00:00

it saves 0000-00-00 00:00:00

What seems to be the problem?

2

Answers


  1. The problem is your date is this

    $registered_year2 =". $registered_year .-00-00 00:00:00"; 
    

    See if $registered_year=2019 then you have . 2019 .-00-00 00:00:00 with dots. Your mixing concatenation up with interpolation. And MySQL date time does not recognize that as a valid date.

    For example, i chose 2018 then i want to save it 2018-00-00 00:00:00

    Well to be sure, 2018-00-00 00:00:00 is not . 2019 .-00-00 00:00:00

    It’s a simple typo.

    Further

    2018-00-00 00:00:00 is not a valid date. So that wont work. But lets look at this:

    want to save year only in my database date_created with type currenttimestamp

    Datetime is not a timestamp. And if you need the year from a datetime field you can use YEAR(datetime_field) in both the select and where parts of the query.

    If you need it from a timestamp, you can cast the timestamp to a DateTime

       YEAR(FROM_UNIXTIME(timestamp_field))
    

    So if you save the current datetime (NOW()) even though I prefer doing this in PHP because the DB has it’s own timezone setting separate from PHP. Then you can just do that when you need the year.

    Cheers.

    Login or Signup to reply.
  2. There are two things to chage. 1st as per the ArtisticPhoenix answer

    $registered_year2 = $registered_year . "-00-00 00:00:00";
    

    make sure that date is 2018-00-00 00:00:00

    Another thing is that change your field type from timestamp to datetime

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search