0
votes

I can't figure out why I am getting this warning: "Warning: Invalid argument supplied for foreach()". This code works locally, but when I pushed to the server I get the warning. Any ideas why?

function updateVIfromScores($client_id, $vi__weight_array){
    $vi = 0;
    $sql = "SELECT * FROM client_vulnerability_scores
        WHERE client_id = $client_id";
    $result = mysql_query($sql) or die('query in updateVIfromScores failed:'.mysql_error().'<br/>sql:'.$sql.'<br/>');
    foreach(mysql_fetch_array($result, MYSQLI_ASSOC) as $key => $value){
        $vi += $vi__weight_array{$key} * $value;
    }
    return $vi;
}
3
try var_dump($result); before loop to see what is the value of $result.Jayson O.
MYSQLI_ASSOC in a msql_* function?Musa
var_dump return "resource(6) of type (mysql result) "rharrison33

3 Answers

3
votes

Your query's probably not returning any results (so foreach isn't operating on an array), you should always check to see if there are results before assuming there are:

$result = mysql_query($sql)
    or die('query inupdateVIfromScoresfailed:'.mysql_error().'<br/>sql:'.$sql.'<br/>');

if(mysql_num_rows($result)){
    foreach(mysql_fetch_array($result, MYSQLI_ASSOC) as $key => $value){
        $vi += $vi__weight_array{$key} * $value;
    }
}
else{
    // log it or something
}

Untested code, but you get the idea hopefully.

Cheers

0
votes

Try this function

function updateVIfromScores($client_id, $vi__weight_array){
    $vi = 0;
    $sql = "SELECT * FROM client_vulnerability_scores
        WHERE client_id = $client_id";
    $result = mysql_query($sql) or die('query in updateVIfromScores    failed:'.mysql_error().'<br/>sql:'.$sql.'<br/>');

    if (is_array($result))
        foreach(mysql_fetch_array($result, MYSQLI_ASSOC) as $key => $value){
            $vi += $vi__weight_array{$key} * $value;
        }
    }
    return $vi;
}
0
votes

echo the below query in php, copy the query from the browser and run against the database in phpmyadmin directly and see whether it returns any results:

echo $sql = "SELECT * FROM client_vulnerability_scores WHERE client_id = $client_id";