繁体   English   中英

PHP函数中的逻辑错误

[英]Logical error in PHP function

我想要做的是生成导航菜单,例如

 <ul>
   <li>
     <ul>
...........
    </ul>
  </li>
 </ul>

从数据库,只有一个查询。 但是一旦执行以下功能,它就不会停止。 (似乎存在逻辑错误)。 请看看,怎么了

<?php

function generateMenu($parent, $level, $menu, $utype) {
    global $db;

    $tree = array();
    $stmt = $db->prepare("select id, parent, name FROM navigation WHERE menu=? AND user_type=?") or die($db->error);
    $stmt->bind_param("ii", $menu, $utype) or die($stmt->error);
    $stmt->execute() or die($stmt->error);

    $stmt->store_result();
    $meta = $stmt->result_metadata();

// the following creates a bind_result string with an argument for each column in the query
// e.g. $stmt->bind_result($results["id"], $results["foo"], $results["bar"]);
    $bindResult = '$stmt->bind_result(';
    while ($columnName = $meta->fetch_field()) {
        $bindResult .= '$results["' . $columnName->name . '"],';
    }
    $bindResult = rtrim($bindResult, ',') . ');';

// executes the bind_result string
    eval($bindResult);
    $stmt->fetch();
    $stmt->close();
    while (list($id, $parent, $name) = $results) {
        $tree[$id] = array('name' => $name, 'children' => array(), 'parent' => $parent);
        if (!array_key_exists($tree[$parent]['children'][$id])) {
            $tree[$parent]['children'][$id] = $id;
        }
    }

    print_r($tree);
}

?>

不知道这是否是问题,但是我建议使用call_user_func_array而不是eval来调用bind_result

$bindResult = array();
while ($columnName = $meta->fetch_field()) {
   // Needs to passed by reference, so that it creates the $results array correctly
   $bindResult[] = &$results[$columnName->name];
}
call_user_func_array(array($stmt, 'bind_result'), $bindResult);

编辑:您的问题是$sql->fetch()需要为每一行而不是一次调用。 该代码永远循环,因为您一直在读取同一行。 尝试这个:

function generateMenu($parent, $level, $menu, $utype) {
    global $db;

    $tree = array();
    $stmt = $db->prepare("select id, parent, name FROM navigation WHERE menu=? AND user_type=?") or die($db->error);
    $stmt->bind_param("ii", $menu, $utype) or die($stmt->error);
    $stmt->execute() or die($stmt->error);

    $stmt->store_result();
    $meta = $stmt->result_metadata();

    $bindResult = array();
    $results = array();
    while ($columnName = $meta->fetch_field()) {
       // Needs to passed by reference, so that it creates the $results array correctly
       $bindResult[] = &$results[$columnName->name];
    }
    call_user_func_array(array($stmt, 'bind_result'), $bindResult);

    while ($stmt->fetch()) {
        list($id, $parent, $name) = $results;
        $tree[$id] = array('name' => $name, 'children' => array(), 'parent' => $parent);
        if (!array_key_exists($tree[$parent]['children'][$id])) {
            $tree[$parent]['children'][$id] = $id;
        }
    }
    $stmt->close();

    print_r($tree);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM