phpmysqlwordpress

Mysql SUM function does not return any value


I have these codes to SUM my quantity column in Mysql in Wordpress, it was working well but out of no where today it acting strange.

If below codes are executed it only return User ID without the value in the query ($newval). Any idea what might be the problem?

<?php
global $current_user;
get_currentuserinfo();
$userID = $current_user->ID;
$products = 1370;

global $wpdb;
$row = $wpdb->get_row("SELECT SUM(product_qty) AS quantity FROM wp_wc_order_product_lookup where customer_id=$userID AND product_id=$products");


$newval = $row->quantity;
echo 'User ID is ' . $userID . ' --> ';
echo 'Sum is ' . $newval;
//IF
if ($newval >= 1) {
        echo 'Lets Vote Now';
} else {
        echo 'You have already VOTE';
        echo $userID;
}

Solution

    1. Don't use get_currentuserinfo() This function has been deprecated. Use wp_get_current_user() instead.
    2. Here you can use get_current_user_id() to get current User ID.
    $userID = get_current_user_id();
    $productID = 1370;
    
    global $wpdb;
    $row = $wpdb->get_row($wpdb->prepare("SELECT SUM(product_qty) AS quantity FROM wp_wc_order_product_lookup WHERE customer_id=%d AND product_id=%d", $userID, $productID));
    
    $newval = $row->quantity;
    echo 'User ID is ' . $userID . ' --> ';
    echo 'Sum is ' . $newval;
    if ($newval >= 1) {
       echo 'Lets Vote Now';
    } else {
       echo 'You have already VOTE';
       echo $userID;
    }