-1

I have a table named 'species' with 3 columns: id, specie, rate.

And I have tried using the following query but it throws the errors:

Fatal error: Uncaught Error: Call to a member function insert() on null in D:\Wordpress\....includes\specie_form.php on line 10

Error: Call to a member function insert() on null in D:\Wordpress.....includes\specie_form.php on line 10

Query

$specie_name= $_POST['specie_name'];
$specie_rate=$_POST['specie_rate'];

    global $wpdb;
    
    $wpdb->insert('species', array( //this is line 10 of error
        'id' => NULL,
        'specie' => '$specie_name',
        'rate' => '$specie_rate'
    ));

This is what my db looks like: enter image description here

Raging Vids
  • 121
  • 1
  • 8
  • 1
    I see no assignment to `$wpdb`. – Serg Sep 05 '21 at 12:31
  • @Serg could you please look into my solution below and tell if that is the ideal way to assign the wpdb, i.e. via `if(!isset($wpdb)) { require_once('../../../../wp-config.php'); require_once('../../../../wp-includes/wp-db.php'); }` – Raging Vids Sep 05 '21 at 12:57

2 Answers2

1

it look like in table species you cannot enter null as a valid value to id column .

look in the table if column id is nullable or not and try to give him a number

if there is an autoincrese option try insert without the id column

$wpdb->insert('species', array(
    'specie' => '$specie_name',
    'rate' => '$specie_rate'
));

this is not the problem with the query but how you access wpdb see

Call to a member function insert() on null WORDPRESS

gal peled
  • 467
  • 5
  • 8
  • Thank you, but still the same errors: Fatal error: Uncaught Error: Call to a member function insert() on null ... Error: Call to a member function insert() on null ... – Raging Vids Sep 05 '21 at 12:26
  • sorry it seemes that the problemis not in the SQL itself but on how you use wpdb in page or plugin see https://stackoverflow.com/questions/29919151/call-to-a-member-function-insert-on-null-wordpress – gal peled Sep 05 '21 at 12:39
  • I disagree with the attached link content, coz there it is suggested to 'only' use wpdb inside a plugin and not directly on a php page. However, in this...https://www.youtube.com/watch?v=gNnf2rRDWEw&t=470s ...video, he runs it directly inside a theme file called wpdb.php. – Raging Vids Sep 05 '21 at 12:45
  • well I am no wordpress / php expert only know SQL here but it may be the – gal peled Sep 05 '21 at 12:51
0

Ok so I managed to solve the issue by including some needed files like so:

 global $wpdb;

    if(!isset($wpdb))
        {
            require_once('../../../../wp-config.php');
            require_once('../../../../wp-includes/wp-db.php');
        }

    $wpdb->insert('species', array(
        'specie' => $specie_name,
        'rate' => $specie_rate
    ));
Raging Vids
  • 121
  • 1
  • 8