1

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);

?>

1
  • 1
    <li><a href="link">anchor</a></li> for this echo '<li><a href="'.$row[0].'">'.$row[1].'</a></li>'; put this in while loop then check Commented Jun 9, 2019 at 15:38

1 Answer 1

2

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>';
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.