0

I am currently redesigning my website to use PHP and databases (opposed to Bootstrap, CSS, and HTML) and I am currently having issues grabbing my links from my database and putting them in my nav menu. I prefer to use a database to prevent the need of re-entering all the links if I eventually decide to change them. The issue is I can't seem to get any HTML output here, and I'm not sure what I'm doing wrong. I am fairly new to PHP so there may be something trivial that I just haven't grasped the concept of but currently this code only displays the bullet point of the <ul> on the page. My database and code are below. The database is confirmed able to connect.

enter image description here

test.php:

require_once('config.php');
$conn = new mysqli($servername, $username, $password, $database);

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT link_title, link_url FROM links ORDER BY link_id";

if ($result = $conn->query($query)) {

    echo '<ul class="nav navbar-nav navbar-right">';
    foreach($result as $link) {
        echo '<li>';
        echo "<a href='{$link->link_url}'>{$link->link_title}</a>\n";
        echo '</li>';
    }
    echo '</ul>';

    /* free result set */
    $result->close();
}

/* close connection */
$conn->close();
1
  • 2
    $result is a mysqli result object. you can NOT foreach it. it's not an array. it should be more like while($link = $result->fetchRow()) { ... } Commented Jul 7, 2016 at 21:14

1 Answer 1

1
if ($result = $conn->query($query)) {

  echo '<ul class="nav navbar-nav navbar-right">';
  while($link = $result->fetch_object()) {
       echo '<li>';
       echo "<a href='{$link->link_url}'>{$link->link_title}</a>\n";
       echo '</li>';
  }
  echo '</ul>';

/* free result set */
$result->free(); // there is no method "close" for result -> http://fi2.php.net/manual/en/class.mysqli-result.php
}
Sign up to request clarification or add additional context in comments.

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.