Wordpress - WPDB Insert or if exists Update
Have you tried $wpdb->replace
. According to WP Codex:
Replace a row in a table if it exists or insert a new row in a table if the row did not already exist.
I have tried myself in some plugins and it does the work when trying to avoid unique IDs duplication errors, etc.
More info in the codex
First, you are using prepare
incorrectly. You seem to have $wpdb->update
's arguments wrapped in $wpdb->prepare
like that. That won't work. In effect, you are passing update
a single argument-- the output of prepare
. Try something simple like the following and you will see why that won't work:
$post_id = 123;
$item_stock = 567;
var_dump(
$wpdb->prepare(
$wpdb->prefix.'item_info',
array(
'post_id' => $post_id,
'item_stock' => $item_stock
),
array('post_id' => $post_id)
)
);
And $wpdb->update()
runs prepare
for you.
Second, if this were me, I skip the helper function bloat and write a proper ON DUPLICATE KEY UPDATE
query:
$sql = "INSERT INTO {$wpdb->prefix}item_info (post_id,item_stock) VALUES (%d,%s) ON DUPLICATE KEY UPDATE item_stock = %s";
// var_dump($sql); // debug
$sql = $wpdb->prepare($sql,$post_id,$item_stock,$item_stock);
// var_dump($sql); // debug
$wpdb->query($sql);
This assumes that post_id
is a UNIQUE
index or PRIMARY KEY
. If your table structure is what I think it is, let the database handle it.