首页 > 解决方案 > 在 PHP mysqli_fetch_row() WHILE 循环中识别列号

问题描述

我试图确定我是否正在查看数组中的第一列。

我什么都没试过,但是google了很多,找不到解决办法。

while($row = mysqli_fetch_row($sql)) {
    echo '<tr>'; 
    foreach ($row as $col) {
        if () //NEED CODE HERE
        echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
    }
    echo '</tr>';
}

标签: php

解决方案


mysqli_fetch_row从结果集中获取“一行数据并将其作为枚举数组返回,其中每列存储在从 0(零)开始的数组偏移量中。” 因此列的键与列顺序相同。

所以你可以这样做:

while($row = mysqli_fetch_row($sql)) {
    echo '<tr>'; 
    foreach ($row as $key => $col) {
        if ($key === 0) {
          echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
        }
    }
    echo '</tr>';
}

但是列会受到数据库结构的变化和 SQL 查询的变化。我个人更喜欢mysqli_fetch_assocmysqli_fetch_object,所以我可以按名称而不是订单号使用列。它不易出错。例如,

while($row = mysqli_fetch_assoc($sql)) {
    echo '<tr>'; 
    foreach ($row as $key => $col) {
        if ($key === 'ip_address') {
          echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
        }
    }
    echo '</tr>';
}

注意:$sql这里应该是mysqli_query结果而不是实际的 SQL 字符串。


推荐阅读