0

The return value of my update query on an empty database table is wrong even though my query syntax seems to be right. The ELSE statement is executed when I run the query on an empty table but no update entry is made in the table. What may be wrong?

    if($wpdb->update( 
        'wp_counter_cookies', 
        array( 
            'visit' => current_time( 'mysql' ), // string
        ), 
        array( 'cookie' => $counter_cookie ), 
        array( 
            '%s'    // value1
        ), 
        array( '%s' ) 
    )=== FALSE)
    {
        $table_name = $wpdb->prefix . 'counter_cookies';

        $wpdb->insert( 
            $table_name, 
            array( 
                'visit' => current_time( 'mysql' ), 
                'cookie' => $counter_cookie,
                'user' => $user,
            ), 
            array( 
                '%s', 
                '%s', 
                '%s' 
            ) 
        );                       
    }
    else
    {
        $ignore = true;
    }
  • What is the output of the $wpdb->update function? Can you assign the update to a variable, and then var_dump the variable? Like $updated = $wpdb->update(); var_dump( $updated ); if( $updated === false ){} – czerspalace Jul 15 '16 at 23:59
  • @czerspalace, This function returns the number of rows updated and not an array, so no need to use var_dump(), (ref: codex.wordpress.org/Class_Reference/wpdb). When I echo the $updated variable, the return value is zero (0). This means my input data supposedly matches what is already in the database, and so no rows will be updated, therefore 0 is returned. If the return value is zero, why is the ELSE block executed rather than the INSERT query?????? – Terungwa Jul 16 '16 at 6:38
  • I asked for var dump so that we can also see what type is being returned, int or bool, since the update function returns the number of rows updated OR false on error. Since you said you receive a zero, you need to use == instead of === – czerspalace Jul 16 '16 at 8:13
  • @czerspalace, The return type is an int, and the == operator works as expected. Thank you. +1 for this response! – Terungwa Jul 16 '16 at 12:48
0

Changing the comparison operator to == instead of strict comparison === as suggested by @czerspalace, solved the problem because on execution of my update function no rows were updated, so 0(int) was being returned . False is only returned if there is an error.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.