foreach语句创建无效参数

时间:2014-07-09 13:53:26

标签: php arrays foreach

我正在尝试将我的sql数组结果传递给foreach语句,以便我可以从另一个文件中的表中访问列。我正在做的一个小错误,并获得无效的参数传递给foreach statament错误。 这是我的代码: dashboard.php

include('includes/dashboard.inc');    
$user_id=$_SESSION['sessad']['user']['dsnr'];
$widgets = array(); 
$sql="SELECT dashboard_widget.name,dashboard_widget.id,dashboard_widget_users.position,dashboard_widget_users.dsnr_dashboard_widget
FROM dashboard_widget_users
INNER JOIN dashboard_widget ON dashboard_widget_users.dsnr_dashboard_widget = dashboard_widget.ID
WHERE dsnr_yw_user =".$user_id."
ORDER BY position";
$sql_results=mysql_query($sql);
while($row = mysql_fetch_array($sql_results))
{
    $widgets[] = $row;  
}

dashboard.inc.php

$widgets=$_POST['widgets'];
foreach ($widgets as $key => $val) 
{
    $name = $val['name'];
    $id=$val['id'];
    $page['content'] .= '
    <div id=recordsArray_'.$name.'>
    <table width="538" cellspacing="0" cellpadding="0" border="0" >
        <tr>
            <td id="'.$name.'">
            </td>
     </tr>
   </table>
   </div>';
}

1 个答案:

答案 0 :(得分:0)

正如我在您的代码中看到的那样,您的代码是面向对象的,并且您没有使用函数。

所以当你在第一行include('includes/dashboard.inc');时,你的代码正在运行,但是$ widgets为null,因为解释器在包含时会执行代码,所以在你的while循环之后移动你的include语句 ,并且您的$widgets变量不应为空,并且您将获得html结果。

编辑:从widgets.inc.php中删除此行$widgets=$_POST['widgets'];

  

注意:我只是预测你要从代码中做什么,正如我所看到的那样   您不需要$ _POST [&#39;小部件&#39;]您只想打印小部件   来自数据库,否则如果不是,我错了,请澄清你的   评论中的问题。

编辑2

   $user_id=$_SESSION['sessad']['user']['dsnr'];
    $widgets = array(); 
    $sql="SELECT dashboard_widget.name,dashboard_widget.id,dashboard_widget_users.position,dashboard_widget_users.dsnr_dashboard_widget
    FROM dashboard_widget_users
    INNER JOIN dashboard_widget ON dashboard_widget_users.dsnr_dashboard_widget = dashboard_widget.ID
    WHERE dsnr_yw_user =".$user_id."
    ORDER BY position";
    $sql_results=mysql_query($sql);
    while($row = mysql_fetch_array($sql_results))
    {
        $widgets[] = $row;  
    }
include('includes/dashboard.inc'); 

和widgets.inc.php

foreach ($widgets as $key => $val) 
{
    $name = $val['name'];
    $id=$val['id'];
    $page['content'] .= '
    <div id=recordsArray_'.$name.'>
    <table width="538" cellspacing="0" cellpadding="0" border="0" >
        <tr>
            <td id="'.$name.'">
            </td>
     </tr>
   </table>
   </div>';
}