$wpdb->replace / Replace or update primary key

I write code to save data in to the database table.

I want Replace a row in a table if it exists or insert a new row in a table if the row did not already exist.

http://codex.wordpress.org/Class_Reference/wpdb

I use $wpdb->replace function and then add $wpdb->insert_id to end of code.

For Update all fields , I using replace ‘id’ That is primary key.

I add the id field to array

   $wpdb->replace( $wpdb->prefix . 'fafa', 
   array( 
   'id',
   'title' =>  trim($row->item(0)->nodeValue) ,
   'liveprice' =>  trim($row->item(2)->nodeValue)  ,
   'changing' =>   trim($row->item(4)->nodeValue)  ,
   'lowest' =>   trim($row->item(6)->nodeValue)  ,
   'topest' =>   trim($row->item(8)->nodeValue)  ,
   'time' =>   trim($row->item(10)->nodeValue)   ), 
   array( 
   '%d',
   '%s',
   '%s',
   '%s',
   '%s',
   '%s',
   '%s'
) );
 $wpdb->insert_Id;

3 Answers
3

You Can use This solution..

How to delete all records from or empty a custom database table?

In this solution First delete all records an then insert new records

(your table should be have records before to delete query because If run $delete you give error ‘No find row’ ) and No need to use replace I us insert

add this following query before your function. (this query delete all records )

$delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`");




$delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`"); /// delete all records

   $wpdb->insert( $wpdb->prefix . 'fafa', 
   array( 
   'title' =>  trim($row->item(0)->nodeValue) ,
   'liveprice' =>  trim($row->item(2)->nodeValue)  ,
   'changing' =>   trim($row->item(4)->nodeValue)  ,
   'lowest' =>   trim($row->item(6)->nodeValue)  ,
   'topest' =>   trim($row->item(8)->nodeValue)  ,
   'time' =>   trim($row->item(10)->nodeValue)   ), 
   array( 
   '%s',
   '%s',
   '%s',
   '%s',
   '%s',
   '%s'
) );

run foreach

Note: If your code is in a loop you should insert this query before loop.

     $delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`");
    foreach (){

// code

    }

Leave a Comment