Get PHP Fatal error on globalized $wpdb: Call to a member function insert() on a non-object- I have no clue. What to do?

I am trying to utilize this function. I cannot figure out why I am still getting the PHP error. All I can figure out is that for some reason the template isn’t able to access $wpdb. I don’t know what line needs to be placed in the functions.php (in theme folder) file that contains this function. Please help me!!

function submitWeightUpdate( $userid, $weight ) {
    global $wpdb;

    $result = $wpdb->insert( 'wp_weights', array( 'user_id' => $userid, 'current_weight' => $weight ), array( '%d', '%d' ) );

    if (empty($_POST['weight'])) {
        $return['error'] = true;
        $return['msg'] = 'You did not enter a weight.';
    }
    else {
        $return['error'] = false;
        $return['msg'] = 'You've entered: ' . $weight . ' as your new weight.';
    }

    echo json_encode($return);
} 

I also tried setting the theme to the default one and it still won’t work, so I have no idea what could be wrong with it!

Related posts

Leave a Reply

3 comments

  1. You did everything right with the globalize, the error message is just telling you that you called a function on $wpdb which does not exists.

    Just check prior you do that $wpdb contains the object you’re intersted in:

    if (is_object($wpdb) && is_a($wpdb, 'wpdb')) {
        $result = $wpdb->insert( 'wp_weights', array( 'user_id' => $userid, 'current_weight' => $weight ), array( '%d', '%d' ) );
    }
    

    Alternatively you can add this below the global line to learn more:

    global $wpdb;
    var_dump($wpdb); // dump variable type and contents.
    

    Additionally try:

    require_once( ABSPATH . 'wp-load.php' );
    global $wpdb;
    

    You might not have wordpress ready to provide what you need in $wpdb.

  2. It’s likely that $wpdb has been globalized when it hits your particular function. Try checking $GLOBALS and if it there is an entry for $wpdb remove the line $global $wpdb; at the start of your funciton.

  3. I faced this frustrating problem. None of the core functions were working.

    So I included this:

    require( '../../../wp-load.php' );
    

    As a better practice:

    if(!defined(ABSPATH)){
        $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
        var_dump($parse_uri);
        $parse_uri = str_ireplace('index.php', 'wp-load.php', $parse_uri);
        require_once( $parse_uri[0]);
    }