sql query in shortcode not working

I have worked it out and here are the steps to what I did to get it working

  1. created a custom table in the wordpress database (called it wp-products)
  2. this table had the following fields: id, make, model, price
  3. Created a shortcode to retrieve the price. Shortcode looks like this [product_price id=2] where id=2 is the price value for item 2 in the table.
  4. wrote the shortcode function for this and put it in functions.php in my themes directory.
  5. Modified my original code by
  • adding $table_name = $wpdb->prefix . ‘products’;
  • Changed the query to: $product_price = $wpdb->get_results(“SELECT price FROM ” . $table_name .” WHERE id={$product_id}”, ARRAY_A);
  • changed the foreach statement to $output = $the_price[‘price’];
  1. added the shortcode into the page location where I wanted to display the code.

Here is the code that works, I hope it helps

function product_price_func( $atts ) {
    global $wpdb;

$table_name = $wpdb->prefix . 'products';

$atts = shortcode_atts(
array(
  'id' => 'no id found',
), $atts, 'product_price' );

$product_id = $atts['id'];

$product_price = $wpdb->get_results("SELECT price FROM " . $table_name ." WHERE id={$product_id}", ARRAY_A);

foreach ( $product_price as $the_price ) 
  { 
    $output = $the_price['price'];
  }

return "Product Price: $" . $output;

}
add_shortcode( 'product_price', 'product_price_func' );