What I’m trying to do is, to generate nav menu like
<ul>
<li>
<ul>
...........
</ul>
</li>
</ul>
from db, with one and only query. But onceI execute following function, it doesn’t stop. (Seems there is logic error). Please take a look, what’s wrong
<?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);
}
?>
Not sure if this is the issue, but I’d suggest using
call_user_func_arrayinstead ofevalto callbind_result.EDIT: Your issue is that
$sql->fetch()needs to be called for each row, not just once. The code loops forever because you keep reading the same row. Try this: