0

This is in my theme's functions.php. I have an external MySQL database that I'm connecting to in WordPress with the following code, and I'm attempting to create a shortcode that shows the total of a column named total_downloads, with rows filtered by another column utm_campaign. The table name is reports_downloads. So, line 3 of my code returns the string "apple" and I want to get the sum of total_downloads for apple.

The problem is that this outputs Array ( ) on the page instead of a readable number. I'm struggling with PHP and more so with DB queries, but I'm trying to learn. Any guidance on how to get this function to return the integer 2?

utm_campaign total_downloads
apple 1
orange 1
apple 1
function getAllDownloads() {
    $wpdb2 = new WPDB( 'db_user', 'db_pass', 'db_name', 'db_host');
    $utm = do_shortcode('[wpmem_field utm_campaign]');
    $result = $wpdb2->get_results("SELECT SUM(total_downloads) as result_value FROM reports_downloads WHERE utm_campaign = ".$utm."");
    print_r($result);
    echo $result[0]->result_value;
}
add_shortcode('b3_all_downloads', 'getAllDownloads');
New contributor
Adam ImaginedAtom Mitchell is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • The $result[0]->result_value (if it's set) should give you the correct value, however, you might instead just use wpdb::get_var(), and you should also use wpdb::prepare() instead of passing an insecure SQL command with a dynamic value (of the $utm variable in your case). See the wpdb documentation for more details. Also, just a reminder that shortcode should always return the output, so for example you'd do return $result[0]->result_value; instead of echo $result[0]->result_value;.
    – Sally CJ
    Jun 23 at 1:13

0

Your Answer

Adam ImaginedAtom Mitchell is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.