mysql – User set date and time from frontend doesn’t get stored into database

Question

My application lets users store diary entries into a database table. They are free to set the date and time to what they need using html inputs (so I can’t simply use the current time because they might want to create an entry in the past).

I’m able to send the date and the time forward as a POST request. Here’s how the header looks like:

action: send_daily_event
weight: 
dateAndTime: 2021-06-01 19:08:00

In the database I have a table called “dailyevents”. It has a column called “dateAndTime” with the type “datetime”.

The database entries are recorded to the table otherwise, but the dateAndTime column remains always 0000-00-00 00:00:00 for each entry.

Here is the relevant part from my functions.php:

function sendDailyEvent(){

    //for storing the logged in user name:
        global $current_user;
        get_currentuserinfo();
        $currUserLoginName = $current_user->user_login;

    $weight = ($_POST["weight"]);

    $dateAndTime = ($_POST["dateAndTime"]);
    
    $sanitizedWeight = sanitize_text_field($weight); /* Checks for problematic things in the string like invalid UTF-8, it converts < characters to entities, strips all tags, removes line breaks, tabs and extra white space. */

    global $wpdb;

    $result_check = $wpdb->insert( 
        'dailyevents',
        array(
            'username' => $currUserLoginName,
            'dateAndTime' => $dateAndTime,
            'weight' => $sanitizedWeight,
            
        ),
        array(
            '%s', 
            '%s', 
            '%d', 

        )
    );

    if($result_check){ //return the response
        echo $result_check;
     }else{
       echo "something went wrong";
     }

    exit();

} /* end send daily event */

My suspicion is that the datetime column in the database doesn’t like the fact that I’m trying to give it a string, but I don’t know how else I should format my $dateAndTime variable.

in progress 0
Antti 2 years 2021-06-01T11:26:56-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-06-02T06:15:41-05:00

    Got it to work by formatting the $dateAndTime string like this before binding it:

    $formattedDateAndTime = date("Y-m-d H:i:s", strtotime($dateAndTime));

Leave an answer

Browse
Browse