努力将 PHP 数组输出为无序列表的 HTML 列表 [英] Struggling to output PHP array as unordered HTML list

查看:32
本文介绍了努力将 PHP 数组输出为无序列表的 HTML 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,这可能是非常基本的.我创建了一个 SELECT 查询,并且(我认为)将检索到的数据存储为一个数组.

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

我自己已经能够使用 printf 从数组中输出选定的项目,但我想以更结构化的方式输出值,作为 HTML 中的无序列表.这将是一个链接列表.anchor 对应于我的 MySQL 表中的链接名称列,link 对应于 url 列,输出为,例如<li><a href="link">anchor</a></li>

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>

这是我所知道的.我知道我需要一个 for 循环,但我复制的演示总是失败.

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

?>

推荐答案

您的代码没有太多可更改的地方.在 while 循环周围添加

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

    虽然我会使用 MYSQLI_ASSOC 而不是 MYSQLI_NUM(这被认为是不好的做法),并且还对 mysqli 函数使用面向对象的风格:

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

    这篇关于努力将 PHP 数组输出为无序列表的 HTML 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆