In this tutorial, I will let you know insert, update and delete record in wordpress. WordPress is a very popular open source in PHP. WordPress has a lot of inbuilt functionalities, which is basic for any website and blog.
Here. We will discuss how to insert, delete and update record using wordpress connection object. WordPress defines a class called wpdb
, which contains a set of functions used to interact with a database. Its primary purpose is to provide an interface with the WordPress database, but can be used to communicate with any other appropriate database.
There are two methods to access $wpdb object:
1- $wpdb: Declared $wpdb
as global and used it to execute an SQL query statement that returns a PHP object.
global $wpdb; $results = $wpdb->function
2- $GLOBALS : Access $GLOBALS
superglobal. Does not require global keywords (but may not be best practice).
$results = $GLOBALS['wpdb']->function
How to insert record using $wpdb:
We can use the insert method to insert data into the database.
$wpdb->insert('table_name', array('id'=>'1', 'name'=>'parvez'));
How to update record using $wpdb:
We can use the update method to insert data into a database.
$wpdb->update('table_name', array('id'=>'1', 'name'=>'parvez', array('id' => '2')));
How To Delete Record using $wpdb
The $wpdb
is having delete()
method to delete the record from wordpress.
wpdb::delete('table', array( 'ID' => 1 ), array( '%d' ) )
nice post but it would be great if you can explaing $wpdb->insert and $wpdb->update functions parameters.
Sure,
$wpdb->insert function takes two parameters(table name and column values) and $wpdb->update function takes three parameters (table name, value and id-which row to update).
Great post.
You can get more info from official docs.
this is a mistake, the parentheses mislocated and form 2 parameters for update:
$wpdb->update(‘table_name’, array(‘id’=>’1’, ‘name’=>’parvez’, array(‘Id’ => ‘2’)));
should be
$wpdb->update(‘table_name’, array(‘id’=>’1’, ‘name’=>’parvez’), array(‘Id’ => ‘2’));
thanks
It has been a while but it would be a bit clearer if we saw what was in the table before and then what was in it after the update.