1

I have two fields that are used to identify a particular row (acting as a composite key). If it does not exist, I wish to insert a new row.

The REPLACE function (http://codex.wordpress.org/Class_Reference/wpdb#REPLACE_row) appears to be exactly what I need.

$wpdb->replace(
    $wpdb->custom_table,
    array('fk_parent'=>$FK_parent,
          'seasonnum'=>$seasonnum_insert
         ),
    array(
        '%d',
        '%d'
    ));

This is not working - it is always inserting a new row and not replacing the row.

The following query will return the COUNT = 5 as expected using the following SQL code in the database

SELECT COUNT(*) FROM customtable1 WHERE 'FK_parent'=1 AND 'seasonnum'=64;  

but the following WPDB class query does not. (the above returns the count as expected whereas the following returns a count of 0 or null)

$count1 = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->custom_table WHERE 'FK_parent'=%d AND 'seasonnum'=%d;",$FK_parent,$seasonnum_insert));

This appears to work if I evaluate using just one variable in the WHERE clause, though.

  • Are either fk_parent or seasonnum unique? If not, how will $wpdb->replace know what needs to be replace? – David Gard Feb 18 '15 at 14:42
  • thanks, yes, that may the issue. neither are unique. So I should retrieve the PK and use that then I suppose. – r4gt4g Feb 18 '15 at 20:13
  • Yes, if there is a unique key you should pass that along with your other data. – David Gard Feb 19 '15 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.