0

I am trying to use $wpdb object to get results from a custom table and I get an error when I echo the result:

Notice: Undefined property: stdClass::$category in...

Here is the PHP code:

global $wpdb;
$prodCat = $wpdb->get_results( 
"SELECT * FROM product_category" , OBJECT_K);
    foreach ( $prodCat as $row ){
                echo $row->category-name;
    }

Any help is appreciated.

1

I have checked your code and I think there are the couple of things you have to consider:

  1. table prefix
  2. column name
  3. validate get_results function output

Firstly, the original prefix is defined in wp-config.php. The WordPress $wpdb class provides a variable $prefix. Always use $wpdb obefore table name and it will automatcially insert the table prefix. Like this:$wpdb->product_category

Secondly, make sure column name is correct. You can view all columns names by dumping the get_results output. e.g: var_dump( $prodCat );

Thirdly, get_results return output as an array. If no data or Database error, the return value will be an empty array and if your query is empty or you pass the invalid output_type i.e: 'OBJECT_K', NULL will be returned. So, always validate your output. e.g: if( $prodCat ).



global $wpdb;

$prodCat = $wpdb->get_results( "SELECT * FROM $wpdb->product_category " , OBJECT_K);

if( $prodCat ) {

    foreach ( $prodCat as $row ) {

       echo $row->category_name;

    }
}

0
1

I think problem is in line

echo $row->category-name;

It should be echo $row->category_name; if your query getting data.

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.