我目前有一些代码连接到数据库,该数据库将获取信息以允许我创建动态菜单。 但由于某种原因,我经常遇到错误。
代码是:
$config['database']['db_host'] = "localhost";
$config['database']['db_port'] = "db";
$config['database']['db_user'] = "db";
$config['database']['db_pass'] = "db";
$config['database']['db_name'] = "db";
function connect_db(){
global $config;
$db = mysql_connect($config['database']['db_host'].":".$config['database']['db_port'],$config['database']['db_user'],$config['database']['db_pass']) or die("Unable to connect mysql server!");
$conn = mysql_select_db($config['database']['db_name']) or die("Database not found in mysql server!");
return $conn;
}
function menu_from_query($query){
global $index;
connect_db();
$result = mysql_query($query);
$menu = array(
'items' => array(),
'parents' => array()
);
while ($items = mysql_fetch_assoc($result)){
$menu['items'][$items['id']] = $items;
$menu['parents'][$items['parent']][] = $items['id'];
$parent = $items['parent'];
while($parent != 0){
if($menu['items'][$parent]['parent'] == 0)
break;
$parent = $menu['items'][$parent]['parent'];
}
$menu['items'][$items['id']]['top_parent'] = $parent;
if($index == $items['link'] && $parent != 0)
$menu['items'][$parent]['class'] = "open";
}
return menu_builder($menu);
}
function menu_builder($menu, $parent = 0){
global $index;
$output = "";
if (isset($menu['parents'][$parent])){
$output .= "";
foreach ($menu['parents'][$parent] as $itemId){
$active = ($index.".html" == $menu['items'][$itemId]['link'])?" class='active'":null;
if(!isset($menu['parents'][$itemId])){
$output .= "".(!empty($menu['items'][$itemId]['icon'])?"":null)."".$menu['items'][$itemId]['title']."";
}
if(isset($menu['parents'][$itemId])){
$dropdown = ' ';
$output .= "".(!empty($menu['items'][$itemId]['icon'])?"":null)."".$menu['items'][$itemId]['title']."$dropdown";
$output .= menu_builder($menu, $itemId);
$output .= "";
}
}
$output .= "";
}
return $output;
}
当我在我的页面中使用以下方式调用它时:
$menu = menu_from_query("SELECT id, title, link, icon, parent FROM menu ORDER BY parent, sort, title");
menu_builder($menu, 0);
我收到错误:
警告:非法字符串偏移'父母' 第47行/var/www/html/assets/php/functions/menu.functions.php
警告:为foreach()提供的参数无效 第47行/var/www/html/assets/php/functions/menu.functions.php
导致错误的原因是什么?如何解决?