如何删除“;警告为foreach()提供的参数无效;在php中?

如何删除“;警告为foreach()提供的参数无效;在php中?,php,mysql,foreach,Php,Mysql,Foreach,我想在php中从数据库中获取不同的值,但得到了以下警告 为foreach()提供的参数无效 如何删除此警告? 这是我的密码: $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($startdat

我想在php中从数据库中获取不同的值,但得到了以下警告

为foreach()提供的参数无效

如何删除此警告? 这是我的密码:

$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;
}       
$startdate1=date($Y-m-d h:i:s',strottime($\u POST['registration\u opens\u date']);
$enddate1=日期($Y-m-d h:i:s',标准时间($_POST['registration\u ends\u date']);
$startdate1=strottime($startdate1);//将日期转换为UNIX时间戳
$enddate1=strotime($enddate1);//将日期转换为UNIX时间戳
$dates=array();
//从开始日期循环到结束日期,并输出其间的所有日期
对于($i=$startdate1;$i query($strQuery)或die($GLOBALS['mysqli']->错误);
而($rs=$result->fetch_assoc()){
$res[]=$rs;
}
$strXML=“”;

对于($i=$startdate1;$i您没有初始化变量,它是空的

在while循环之前添加以下内容:

$res = array();

$res
从未定义。它只在SQL查询的
while()
循环中赋值。如果查询返回一组空白数据,
$res
将未定义,因此PHP将抛出错误

尝试在代码开头将
$res
定义为空白数组:

$res = array();

在foreach之前添加此行:

if(!isset($res) && ! is_array($res)) continue;
终极foreach技巧

if(!empty($rows)) foreach( is_array($rows) ? $rows : array($rows) as $row) {
    // no error possible
}

测试是否设置了$res,并且是循环前的数组错误意味着传递给
foreach
的不是数组。在这种情况下,当循环第一次迭代时,数组尚未定义,并且将抛出该错误消息。首先,使用
$res=array()初始化空数组;
在循环之前。要确保参数始终是数组,可以使用。