I am trying to interact with my wqordpress database.
I need to upload a csv file to my database but it will not run any query, no matter which way I try using the WordPress codex, I cannot get it to do what I need to.

So from my Admin panel, I upload the csv file click sumbmit which then runs the following function.

The error I get is: Fatal error: Call to a member function query() on a non-object in /home/dlaveric/public_html/client-area/clients/client/wp/wp-content/themes/Theme/includes/wine-list/wine-list-functions.php on line 11

Here is my code:

<?php

if (isset ($_POST['Submit']))
{
    upList();
}

function upList(){

    global $wpdb;
    $wpdb->query(
        $wpdb->prepare(
            " DELETE FROM $wpdb->winelist"
        )
    );


    if ($_FILES['csv']['size'] > 0) {

        //get the csv file
        $file = $_FILES['csv']['tmp_name'];
        $handle = fopen($file,"r");

        $data[]='';

        //loop through the csv file and insert into database
        do {
            if ($data[0]) {
                $wpdb->insert(
                    'winelist',
                    array(
                        'item' => addslashes($data[0]),
                        'btlPrice' => addslashes($data[1]),
                        'casePrice' => addslashes($data[2]),
                        'salePrice' => addslashes($data[3])
                    )
                );

            }
        } while ($data = fgetcsv($handle,1000,",","'"));

        $wpdb->get_results( 
            "
            SELECT * 
            FROM $wpdb->winelist    
            ORDER by id
            "
        );

        //throw out table stuff here!
    }
}
?>

It says that $wpdb is not an object so you can not address a method of it. Has $wpdb been initialized as a database object somewhere?

it gets set as gloabl on line 10, its a built in wordpress function. As far as I am aware its used throughout the whole system.

So, what files are you including?

Maybe you check for the existence of the object first (to be on the safe side):

function upList() {

if(!isset($wpdb) || !method_exists($wpdb, 'query')) {
    die('Error accessing database');
}

    global $wpdb;
    $wpdb->query(
    ...

or send the object as an argument (no need to use global keyword):

function upList($wpdb) {

    $wpdb->query(
    ...

Well, this still does not answer why the DB object has not been initialized...

I managed to get it working be calling in my wp-config before my global. that did the trick.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.