Write Custom MySQL Query in WordPress


You can write custom MySQL queries in WordPress using wpdb class. This class provide neccessory functions like insert,update,delete and many others.

Insert Data to MySQL Database
Update Data in MySQL Database
Delete Data from MySQL Database


Insert Data to MySQL Database
This method take three argument
1. Table Name
2. Data to insert
3. Data Format (optional It is like ‘C’ Language style to format data)

Return the number of inserted rows on true, otherwise false on error.

Example :
global $wpdb;
$wpdb->insert(
$wpdb->posts,
array( 'post_title'=>$post_title,
'post_content'=>$post_content,
'post_type'=>'post'),
array('%s','%s','%s')
);


Update Data in MySQL Database
This method take five argument
1. Table Name
2. Data to update
3. Where clause (in column => value pairs)
4. Data Format (optional, It is like ‘C’ Language style to format data)
5. Where Format (optional, It is like ‘C’ Language style to format data)

Return number of updated rows on true ,otherwise return false on error

Example :
global $wpdb;
$wpdb->insert(
$wpdb->posts,
array( 'post_title'=>$post_title,
'post_content'=>$post_content
),
array('ID'=>$post_id),
array('%s','%s'),
array('%d')
);


Delete Data from MySQL Database
This method take three argument
1. Table Name
2. Where clause (in column => value pairs)
3. Where Format (optional, It is like ‘C’ Language style to format)

Return number of deleted rows on true ,otherwise return false on error

Example:
global $wpdb;
$wpdb->delete(
$wpdb->posts,
array('post_tyle'=>'revision'),
array('%s')
);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s