-1

i have this MySQL table for news categories:

id - name - parent

1: now I need to list parent/child categories into <optgroup><optgroup>.

PHP CODE:

$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>";

PROBLEM:

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

UPDATE: I test with $categories array and see my code worked. if $categories MySQL result Like this:

$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'),
);

How To Fix My Problem!?

2: in update news page,I need To select News cats in this menu. My mean is: if $newscatid = $catid selected Option.(option value = $newscatid) How To update my code for this?

Alex.DX
  • 141
  • 1
  • 4
  • 14

2 Answers2

0

You can't just call a query and use it like that. Your query returns a result set and you need to iterate through that. Try this

$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'];
}

Also, you really need to switch to mysqli Why shouldn't I use mysql_* functions in PHP?

Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100
-1

mysql_query function returns Resource not Array , check http://php.net/manual/en/function.mysql-query.php

try this

while($category = mysql_fetch_assoc($categories)){ // LINE 734
  $parent = $category['parent'];
  if (! isset($options[$parent])) $options[$parent] = array();
  $options[$parent][$category['id']] = $category['name'];
}

by the way , you are using deprecated mysql functions ...

ogres
  • 3,660
  • 1
  • 17
  • 16