Thomas Bishop
Thomas Bishop

Reputation: 105

Struggling to output PHP array as unordered HTML list

Apologies as this is probably very basic. I have created a SELECT query and have (I think) stored the data retrieved as an array.

By myself I have been able to use printf to output selected items from the array but I want to output the values in a more structured way, as an unordered list in HTML. It's going to be a list of links. anchor corresponds to the link name column in my MySQL table and link corresponds to the url column, to be output as, e.g <li><a href="link">anchor</a></li>

This is as far as I have got. I know I need a for loop but the demos I've copied keep failing.

Very grateful for any pointers from kind people. Backend is new to me.

<?php
$server = "localhost";  
$username = "blah";
$password = "blahblah";
$database = "blah_db";

$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}       

$result = mysqli_query($conn, "SELECT  anchor, link FROM footerLinks");
   

while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
    printf("Anchor: %s  Link: %s ", $row[0], $row[1]);  
}

mysqli_free_result($result);

?>

Upvotes: 1

Views: 74

Answers (1)

Paul Spiegel
Paul Spiegel

Reputation: 31772

There is not much to change in your code. Add <ul> and </ul> around the while loop. Change the pattern to <li><a href="%s">%s</a></li>. And swap $row[0], $row[1] to $row[1], $row[0]:

$result = mysqli_query($conn, "SELECT  anchor, link FROM footerLinks");

echo '<ul>';
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
    printf('<li><a href="%s">%s</a></li>', $row[1], $row[0]); 
}
echo '</ul>';

I would though use MYSQLI_ASSOC instead of MYSQLI_NUM (which is considered bad practice), and also use the object oriented style for mysqli functions:

$result = $conn->query("SELECT  anchor, link FROM footerLinks");

echo '<ul>';
while ($row = $result->fetch_assoc()) {
    printf('<li><a href="%s">%s</a></li>', $row['link'], $row['anchor']); 
}
echo '</ul>';

Upvotes: 2

Related Questions