我正在尝试构建一个函数,使我能够从数据库表中构建一个简单的导航(或列表,事实)。
问题是,括号中的变量不起作用,我该如何解决?
function buildNav($DbRow, $DbName) {
$nav_qry = "SELECT $DbRow FROM $DbName WHERE 1";
$nav_res = mysqli_query($con, $nav_qry);
echo "<ul>";
while ($row = mysqli_fetch_assoc($nav_res)) {
echo "<li id='" . $row[$DbRow] . "'><a href='?id=" . $row[$DbRow] . "' class='nav-point'>". $row[$DbRow] ."</a></li>";
}
echo "</ul>";
}
谢谢!
答案 0 :(得分:1)
无需与db建立新的联系。只需添加全局变量:
function buildNav($DbRow, $DbName) {
global $con;
//...your sql code goes here
}
答案 1 :(得分:0)
我假设您已经检查过$ nav_res是否已有行。所以,我建议你尝试下面的代码,看看它是否有所不同。
while ($row = mysqli_fetch_assoc($nav_res)) { ?>
<li id='<?php echo $row[$DbRow] ?>'><a href='?id=<?php echo $row[$DbRow] ?>' class='nav-point'><?php echo $row[$DbRow] ?></a></li>
<?php
}
?>
答案 2 :(得分:0)
好吧问题是,函数无法访问文档中前面定义的$ con变量,所以如果它在函数中,整个过程都有效。
function buildNav($DbRow, $DbName) {
$con = mysqli_connect('host', 'user', 'password', 'database');
$nav_qry = "SELECT $DbRow FROM $DbName WHERE 1";
$nav_res = mysqli_query($con, $nav_qry);
echo "<ul>";
while ($row = mysqli_fetch_assoc($nav_res)) {
echo "<li id='" . $row['title'] . "'><a href='?id=" . $row['title'] . "' class='nav-point'>". $row['title'] ."</a></li>";
}
echo "</ul>";
}