警告:为foreach()提供的参数无效

时间:2013-11-02 15:05:50

标签: php mysql

我有新闻类别的MySQL表:

id - name - parent

1: 现在我需要将父/子类别列为<optgroup><optgroup>

PHP代码:

$options    = array();
$categories = mysql_query("
  SELECT 
    id, name, p.name AS parent 
  FROM 
    " . CATS . " AS child
  INNER JOIN
    " . CATS . " AS p ON p.id = child.parent
");
foreach($categories as $category) { // LINE 734
  $parent = $category['parent'];
  if (! isset($options[$parent])) $options[$parent] = array();
  $options[$parent][$category['id']] = $category['name'];
}
echo "<select>";
foreach($options as $group => $option) {
  printf('<optgroup label="%s">', $group);
  foreach ($option as $id => $label) {
    printf('<option value="%s">%s</option>', $id, $label);
  }
  printf('</optgroup>');
}
echo "</select>";

问题:

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\cms\news.php on line 734

更新:我使用$categories array进行测试,看看我的代码是否有效。 if $ categories MySQL结果像这样:

$categories = array(
  array('id' => 1, 'name' => 'Label 1', 'parent' => 'Parent 1'),
  array('id' => 2, 'name' => 'Label 2', 'parent' => 'Parent 2'),
  array('id' => 3, 'name' => 'Label 3', 'parent' => 'Parent 1'),
  array('id' => 4, 'name' => 'Label 4', 'parent' => 'Parent 1'),
  array('id' => 5, 'name' => 'Label 5', 'parent' => 'Parent 1'),
  array('id' => 6, 'name' => 'Label 6', 'parent' => 'Parent 3'),
  array('id' => 7, 'name' => 'Label 7', 'parent' => 'Parent 8'),
  array('id' => 8, 'name' => 'Label 8', 'parent' => 'Parent 4'),
);

如何解决我的问题!?

2:在更新新闻页面中,我需要在此菜单中选择新闻猫。我的意思是:如果$newscatid = $catid选择了选项。(option value = $newscatid)如何更新我的代码?

2 个答案:

答案 0 :(得分:0)

您不能只是调用查询并像这样使用它。您的查询返回结果集,您需要迭代它。试试这个

$query = mysql_query("
  SELECT 
    id, name, p.name AS parent 
  FROM 
    " . CATS . " AS child
  INNER JOIN
    " . CATS . " AS p ON p.id = child.parent
");
while($category = mysql_fetch_assoc($query)) {
  $parent = $category['parent'];
  if (! isset($options[$parent])) $options[$parent] = array();
  $options[$parent][$category['id']] = $category['name'];
}

此外,您确实需要切换到mysqli Why shouldn't I use mysql_* functions in PHP?

答案 1 :(得分:-1)

mysql_query函数返回Resource not Array, 检查http://php.net/manual/en/function.mysql-query.php

试试这个

while($category = mysql_fetch_assoc($categories)){ // LINE 734
  $parent = $category['parent'];
  if (! isset($options[$parent])) $options[$parent] = array();
  $options[$parent][$category['id']] = $category['name'];
}
<顺便说一下,你使用的是不推荐使用的mysql函数......