WPDB Insert or if exists Update

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.

Leave a Comment