0

I'm trying to build a function which enables me to build a simple Navigation (or list, matter of fact) from a database table.

Problem is, the variables in the brackets don't work, how can I fix this?

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

Thanks!

3 Answers 3

1

No need to make a new conenction to db. Just add the global variable thus:

function buildNav($DbRow, $DbName) {
    global $con;
    //...your sql code goes here
}

See http://php.net/manual/en/language.variables.scope.php

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I just realized :)
0

I assume you already checked if $nav_res has rows already. So, I suggest you to try the below code to see if it makes any difference.

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
  }
?>

3 Comments

Thats not working :-/ <nav> <ul></ul> </nav>
can you print_r the $nav_res please and also print_r the $row in the while.
the print_r for $nav_res is 1, I'm not getting any for $row, in fact none of the echo commands I use inside the while-loop is printed, so its not iterating. But if I enter the query in phpmyadmin, I get results
0

Allright the problem is, the function cannot access the $con variable defined earlier in the document, so If its in the function, the whole thing works.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.