How to get array value from wordpress database get_results
Asked Answered
P

2

7

Trying to echo the array value from my mysql query (inside Wordpress snippet)

function get_customer_gain() {
  global $wpdb; 
  $users = $wpdb->get_results( "SELECT SUM(wp_wpdatatable_1.payback) FROM wp_wpdatatable_1");
  foreach( $users as $user ) {
    echo $user;
  }
}
add_shortcode('customer_gain', 'get_customer_gain');

my var_dump is: array(1) { [0]=> object(stdClass)#3098 (1) { ["SUM(wp_wpdatatable_1.payback)"]=> string(6) "183320" } }

So basically im trying to echo that 183320 number

Any guidance would be appreciated.

Thanks

Pricillaprick answered 20/10, 2017 at 10:20 Comment(1)
just use $number = $wpdb->get_var(SELECT SUM(...";Finding
S
5

You have to use the correct syntax $wpdb->get_results( $query, $type_of_result);

check this out here

EDIT FOR EXPLAINATION:

$users = $wpdb->get_results( "SELECT SUM(wp_wpdatatable_1.payback) as sumed FROM wp_wpdatatable_1", ARRAY_A);

The array_a will retur associative array while by default it returns as object that cause problem

Shipe answered 20/10, 2017 at 10:26 Comment(3)
accepted param : ARRAY_A || ARRAY_N || OBJECT || OBJECT_KShipe
once the output is done by ARRAY_A you can access the valueShipe
This is the better solution if already know there is only one row.Creekmore
O
3

Hi and welcome to stackoverflow

Your code must change to

function get_customer_gain() {
  global $wpdb; 
  $users = $wpdb->get_results( "SELECT SUM(wp_wpdatatable_1.payback) as sumed FROM wp_wpdatatable_1");
  foreach( $users as $user ) {
    echo $user->sumed;
  }
}
add_shortcode('customer_gain', 'get_customer_gain');
Olathe answered 20/10, 2017 at 10:29 Comment(1)
if I could ask another question... if i use the same code to get a value from another column... then i want to get the difference between those two? from the example above (SELECT SUM(wp_wpdatatable_1.payback... then SELECT SUM(wp_wpdatatable_1.car ...Pricillaprick

© 2022 - 2024 — McMap. All rights reserved.