-1

我有这个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并看到我的代码有效。如果 $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.( option value = $newscatid) 如何为此更新我的代码?

4

2 回答 2

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 为什么我不应该在 PHP 中使用 mysql_* 函数?

于 2013-11-02T15:13:30.467 回答
-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 函数...

于 2013-11-02T15:14:55.300 回答