1

I have a custom table in database named wp_tasks which has 5 fields.

But I am unable to insert the current time to assign_date field.

wp_tasks table

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
worker_id INT(6) ,
project_id INT(6),
work_id INT(6),
assign_date DATETIME

Inserting records

function insert_record_to_db( $worker_id, $work_id, $project_id ){
    global $wpdb;
    $tablename = $wpdb->prefix.'tasks';
    $data = array(
        'id' => "",
        'worker_id' => $worker_id,
        'project_id' => $project_id, 
        'work_id' => $work_id,
        'assign_date' => date( "Y-m-d H:i:s" )
    );
    $format= array( '%d', '%d', '%d','%s');
    $wpdb->insert( $tablename, $data, $format );
}

What is the problem?

  • 1
    You've just forgot a value in the $format array. There are 4 values but in the $data array you have 5. It's to be equal. – Emetrop May 2 '15 at 15:08
  • 1
    or just remove 'id' => "", – shanebp May 2 '15 at 16:42
0

The simplest thing to do here is remove the:

'id' => "",

from the data array.

Also, to simplify your database creation, you don't need to do your get_var(), you can just change your SQL command to:

CREATE TABLE IF NOT EXISTS $table_name

This way you let the db handle creation of the table without the need of an extra SQL statement before hand.

| improve this answer | |
0

Try this one. This should be work for you

function insert_record_to_db( $worker_id, $work_id, $project_id ){
    global $wpdb;
    $wpdb->insert(
        $wpdb->prefix . 'tasks',
        array(
            'worker_id' => $worker_id,
            'work_id' => $work_id,
            'project_id' => $project_id,
            'assign_date' => date( 'Y-m-d H:i:s', current_time('timestamp') )
        ) 
    );
    // $wpdb->insert_id;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.