php - 在 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>';
}
解决方案
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_assoc或mysqli_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 字符串。
推荐阅读
- python-3.x - Python:在站点包文件夹中的 docker 容器中安装本地包
- powerbi - RANKX 没有给出正确的结果
- postgresql - 使用 Linq2DB for PostgreSQL 按周分组
- java - 发出 java gradle “找不到 org.jnetpcap:jnetpcap:1.4.1。”
- azure - 在 Azure 构建管道中创建构建时触发存储库中的特定项目
- java - 将带有密钥动态的json转换为POJO .. java spring boot
- r - 如何分组两次?
- java - java - 如何使用Java中的嵌套for循环生成那么多编号的字母行?
- xampp - 为什么 Sequel Pro 无法连接到 Catalina 上的本地 XAMPP 服务器?
- ios - 如何检测授权对话框 Core Motion 的结果?