Error using WordPress $wpdb object to get result from custom table

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;

    }
}