• Resolved rkvisit

    (@rkvisit)


    PHP Fatal error: Call to a member function insert() on a non-object
    My function is this..

    function setdb($email){
            global $wpdb;
            $set_mail=$email;
            $table_name = $wpdb->prefix . 'nd_tempemails';
            $result=$wpdb->insert(
                $table_name,
                array('email'=>$set_mail
                )
            );
    }

Viewing 4 replies - 1 through 4 (of 4 total)
  • First of all try to see if the $wpdb->prefix points to correct prefix.
    Secondly you could use a prepare statement, which is better to protect from SQL injections

    function setdb($email){
        global $wpdb;
        $tablename = $wpdb->prefix.'nd_tempemails'
        $wpdb->query( $wpdb->prepare(
          "
            INSERT INTO $tablename
            ( 'email' )
            VALUES ( %s )
          ",
          $email
        ) );
    }

    tl:dr: Your code isn’t running inside WordPress and therefore, $wpdb is not defined. You can fix it by requiring wp-load.php prior to calling your function.

    You’re getting this error because you are calling this function from outside of WordPress.

    “Call to a member function insert() on a non-object” means that PHP is looking to see if $wpdb is defined as a WordPress Database Access Abstraction Object, but it is not. In fact, the way you have called it, it is basically null.

    Therefore, when you set $table_name, it is actually just ‘nd_tempemails’ and when you call $wpdb->insert, PHP can’t do as you request because it has no idea what $wpdb is, other than null.

    You can get access to $wpdb from outside WordPress by requiring wp-load.php. See this thread on how you can go about that, and note that how you find the path to wp-load.php depends largely on how your server is set up. That said, generally speaking this will work:

    $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
    require_once( $parse_uri[0] . 'wp-load.php' );
    Thread Starter rkvisit

    (@rkvisit)

    you both gave me the answer.i mean yeah i found that the case is my script is not inside WordPress.as new to this it took me some time to figure it out.But Doug Vanderweide’s explanation is splendid.the next is security case ditikos mentioned.i learned a lot as you both guided me to the correct path! Thank a lot guys!

    Moderator Bet Hannon

    (@bethannon1)

    If you have had your issue resolved, it would be great if you could come back and mark it resolved. This helps us as we sort through people who still need help.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Fatal error when add a record to WordPress table’ is closed to new replies.