How to insert data into WordPress database tables

In this tutorial, we will talk about inserting a new record into an existing table in the WordPress database. The following code snippet will insert a new record for the given 3 fields (post_id, vote, user_id) in the table votes(wp_votes). Remember it will auto-generate values for some fields like ID(Auto increment), TIMESTAMP, etc. If those fields were defined while creating the Table.

global $wpdb;
$table_name = $wpdb->prefix . 'votes'; // Table name
$post_id = 1234; // static value for demonstration purpose only
$vote = 1; // static value for demonstration purpose only
$user_id = get_current_user_id();
$wpdb->insert($table_name, array('post_id' => $post_id, 'vote' => $vote, 'user_id' => $user_id)); 
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us