0

I used "wpdb" in my code But it was not working and the following error:

Fatal error: Call to a member function insert() on a non-object

Notice: Trying to get property of non-object" in tablename = $wpdb->prefix.'complaint';

global $wpdb;
    $name = $_POST["name"];
    $email = $_POST["email"];
    $dis = $_POST["dis"];
    $code = $_POST["code"];

function insert_record_to_db($name,$email,$dis){
    global $wpdb;
$tablename = $wpdb->prefix.'complaint';
    $data=array( 
            'name' => '$name',
            'email' => '$email',
            'dis' => '$dis'
        );
    $format= array('%s','%s','%s');

    $wpdb->insert( $tablename , $data , $format );
};
insert_record_to_db($name,$email,$dis);
  • 2
    Firstly, remove the quotes around the variables in the $data array. Secondly, you have much more $format than $data elements. – Nicolai Jul 27 '15 at 16:02
  • 1
    where is this code and when do you try to call it? – Milo Jul 27 '15 at 16:39
2

This error:

Fatal error: Call to a member function insert() on a non-object

Means that $wpdb isn't instantiated so you are running your code too early or out of WordPress context-- for example, in an exterior PHP file accessed directly, which is what I suspect (Poorly conceived AJAX request perhaps?).

As mentioned, the code has more formats that data elements and your single quotes are going to cause this fail (in a sense) anyway as you will literally be inserting "$email" and "$name" strings into the database.

function insert_record_to_db($name,$email,$dis){
  global $wpdb;
  $tablename = $wpdb->prefix.'complaint';
  $data=array( 
    'name' => $name,
    'email' => $email,
    'dis' => $dis
  );
  $format= array('%s','%s','%s');
  $wpdb->insert( $tablename , $data , $format );
};
insert_record_to_db('a','b','c');

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.