How to use update and delete query in wordpress

First i write manually update, delete, insert and select query and execute data with mysql_query function

Like this:

Read More

Select query

$prefix = $wpdb->prefix;
$postSql = "SELECT DISTINCT post_id
            FROM " . $prefix . "postmeta As meta
            Inner Join " . $prefix . "posts As post
            On post.ID = meta.post_id
            Where post_type = 'product' 
            And post_status = 'publish'
            And meta_key Like '%product_img%'";
$postQry = mysql_query($postSql);
while ($postRow = mysql_fetch_array($postQry)) {
     $post_id = $postRow['post_id'];
}

Insert Query

$insert_images = "Insert Into " . $prefix . "postmeta(post_id,meta_key,meta_value) Value('$post_id','$meta_key','$data_serialize')";
        mysql_query($insert_images);

Update Query:

$update_price = "Update " . $prefix . "postmeta
                         Set meta_key = 'wpc_product_price'
                         Where post_id = $supportMetaID
                         And meta_key Like '%product_price%'";
 mysql_query($update_price);

Delete Query

mysql_query("Delete From " . $prefix . "postmeta Where meta_key IN ('product_img1','product_img2','product_img3')");

All queries are working perfectly … but now i want to embed all queries in wordpress queries.

I can also use wordpress queries like

$wpdb->get_results( "SELECT id, name FROM mytable" );
$wpdb->insert( 
    'table', 
    array( 
        'column1' => 'value1', 
        'column2' => 123 
    ), 
);
$wpdb->update( 
    'table', 
    array( 
        'column1' => 'value1',  // string
        'column2' => 'value2'   // integer (number) 
    ), 
    array( 'ID' => 1 )
);
$wpdb->delete( 'table', array( 'ID' => 1 ) );

But you can see that i use and / or conditions in my queries. So any body help me how can i embed my queries in wordpress

Related posts

Leave a Reply

2 comments

  1. Use $wpdb->prepare for the queries involving different criteria

    $wpdb->query( 
        $wpdb->prepare( 
            "Update " . $prefix . "postmeta
             Set meta_key = %s
             Where post_id = %d
             And meta_key Like '%product_price%'" ,
             'wpc_product_price',$supportMetaID 
            )
    );
    

    Also if your are inserting/deleting from postmeta is suggest you to use WP’s builtin functions update_post_meta/delete_post_meta

  2. Well you can do it the wordpress way and all the security issues are already taken care by wordpress.

    Adding/updating a post meta is as simple as

    update_post_meta( $post_id , 'key', 'value');
    

    Fetching the post meta is as simple as

     get_post_meta( $post_id , 'key', TRUE);
    

    (Here true will return as a single variable, if you are expecing an array use FALSE.)

    Deleting a post meta is simple as

    delete_post_meta($post_id , 'key');