Inserting records

The wpdb class provides a built-in insert function to insert records to custom database tables. So, we need to use it for better performance, instead of writing INSERT queries from scratch. Let's take look at the syntax of insert function:

$wpdb->insert(  'table',  array( 'column1' => 'value1', 'column2' => 'value2' ),  array( '%s', '%d' ));

The first parameter takes the table name. You need to specify the custom table name with the WordPress database prefix. The next parameter uses an array of column names and respective values. The final parameter defines the correct format for the fields defined in the previous array. We can get number of affected rows on success and false as a return value on failure.

Get WordPress Development Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.