How to insert data in WordPress database table?

To insert data into a WordPress database table we first need to connect the database. If you do not know how to connect the database, you can go and see here. How to connect to WordPress database.

We have to use this object $wpdb to insert data into a database table.

function object_function() {
global $wpdb;
}

The code $wpdb above is needed to make a connection to the database.

You can also insert data through SQL, in the WordPress database table.

$sql = "INSERT INTO tablename (emp_name, emp_phone, emp_email) VALUES ('Doe', '+968956397553', 'info@example.com')";

But we insert data using $wpdb object in WordPress

We have created an employee table “wp_employee” . Where column names are id, emp_name, emp_phone, emp_email.

How to insert data in WordPress database table?

Here we will use $wpdb->insert() function for insert data in database table.

wpdb::insert( string $table, array $data, array|string $format = null )

Where Parameters are:-

  1. $table (string) (Required) Table name.
  2. $data (array) (Required) Data to insert (in column_name => ‘value’).
  3. $format (array|string) (Optional).

How to use this $wpdb->insert() function.

Here call Global variable ($wpdb) for get database connection. $wpdb->prefix is wp_ which is set in wp-config.php file.

global $wpdb;
$table = $wpdb->prefix.'employee';
$data = array(
             'emp_name' => 'John Deo', 
	     'emp_phone' => '+969563895',
	     'emp_email' => 'info@ex.com'
              );

$insert =  $wpdb->insert($table,$data);
if($insert){
          echo 'Data inserted';
          }else 
           {
	   echo 'Data insert failed';
           }

OR using variable

global $wpdb;
$table = $wpdb->prefix.'employee';
$emp_name = 'John Deo';
$emp_phone = '+969563895';
$emp_email = 'info@ex.com';
$data = array(
             'emp_name' => $emp_name, 
	     'emp_phone' => $emp_phone,
	     'emp_email'=> $emp_email
              );

$insert =  $wpdb->insert($table,$data);
if($insert){
          echo 'Data inserted';
          }else 
           {
	   echo 'Data insert failed';
           }

In this code array keys are table column names. In this database table id is a primary key, no need assign a value for id. Because the primary key id auto-generates.
array-code-table
column-names-table
After data inserted table
data-insert-table

Leave a Reply

Your email address will not be published. Required fields are marked *