-1

I want to get distinct values from database in php but i got this warning

Invalid argument supplied for foreach()

How i remove this warning? here is my code:

$startdate1=date('Y-m-d h:i:s',strtotime($_POST['registration_opens_date']));
$enddate1=date('Y-m-d h:i:s',strtotime($_POST['registration_ends_date']));
$startdate1  = strtotime($startdate1 ); // Convert date to a UNIX timestamp  
$enddate1  = strtotime($enddate1 ); // Convert date to a UNIX timestamp  
$dates=array();
// Loop from the start date to end date and output all dates in between  
for ($i = $startdate1; $i <= $enddate1 ; $i += 86400) {
    $dates[$i]=date("m-d-Y", $i);
}
$strQuery="select Distinct DATE_FORMAT(transactions.transaction_date,'%c-%d-%Y') as transaction_date,sum(amount)as Amount from transactions where transaction_date BETWEEN '".$startdate1."' AND '".$enddate1."' group by  DATE_FORMAT(transactions.transaction_date,'%c-%d-%Y')";
$result = $GLOBALS ['mysqli']->query ($strQuery) or die ($GLOBALS ['mysqli']->error . __LINE__);
while($rs=$result->fetch_assoc ()){
    $res[]=$rs;
}
$strXML = "<chart caption='Reports of transactions' showValues='0' xAxisName='Date' yAxisName='Amount' useRoundEdges='1' palette='3'>";
for ($i = $startdate1; $i <= $enddate1 ; $i += 86400) {
    foreach($res as $r){
        if($r['transaction_date']==$dates[$i]){
            $substrXML  .= "<set label='" .$r['transaction_date'] ."' value='" .$r['Amount'] ."' />";
            break;
        }
        else {
            $substrXML = "<set label='".$dates[$i]."' value='0'/>";
        }
    }
    $strXML .=$substrXML;
}       
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
Muhammad Arif
  • 1,014
  • 3
  • 22
  • 56
  • Test if $res is set, and is an array before the loop – Mark Baker Feb 01 '14 at 15:50
  • The error means what you pass to `foreach` is **not** an array. In this case, when the loop iterates for the first time, the array isn't defined yet, and that error message will be thrown. First of all, initialize an empty array using `$res = array();` before the loop. To make sure the argument is ***always*** an array, you can use [`is_array()`](http://php.net/is_array). – Amal Murali Feb 01 '14 at 15:52

4 Answers4

1

Immediately before the foreach add this line:

if(!isset($res) && ! is_array($res)) continue;
krowe
  • 2,129
  • 17
  • 19
0

You are not initializing your variable and it's empty.

Add this before your while loop:

$res = array();
Hardy
  • 5,590
  • 2
  • 18
  • 27
0

$res is never defined. It is only ever assigned values inside your while() loop from your SQL query. In case the query returns a blank set of data, $res will be undefined and thus PHP will throw an error.

Try defining $res as a blank array at the start of your code:

$res = array();
BenM
  • 52,573
  • 26
  • 113
  • 168
0

Ultimate foreach trick

if(!empty($rows)) foreach( is_array($rows) ? $rows : array($rows) as $row) {
    // no error possible
}
pirs
  • 2,410
  • 2
  • 18
  • 25