mysqli_fetch_array()foreach循环重复

 沈驰27 发布于 2023-02-09 15:41

我正在对返回的数据库执行请求array.我正在使用foreach循环来遍历值.

数据库(只有1个条目)

id | field1 | field2 | field3 | field4 | field5
---|--------|--------|--------|--------|--------
1  | value1 |        | value3 | value4 | value5

PHP源代码

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$q = mysqli_query($mysqli, "SELECT * FROM my_table");

echo "
    "; while($q = mysqli_fetch_array($q)) { foreach ($q as $key => $value) { if($value != NULL) { echo "
  • ".$value . "
  • "; // Line below used to show column name and corresponding value //echo "
  • {$key} / {$value}
  • "; } } } echo "
";

预期的HTML输出

  • value1
  • value3
  • value4
  • value5

电流输出

  • 1
  • 1
  • value1
  • value1
  • value3
  • value3
  • value4
  • value4
  • value5
  • value5

目前的问题

As you can see, I current have everything in double, and for some wierd reason, I'm getting the row ID, or so I assume considering I do not get a second row when I add a new row to the database.

Alternate code

Using the commented line, I get this output:

  • 0 / 1
  • id / 1
  • 1 / value1
  • field1 / value1
  • 3 / value3
  • field3 / value3
  • 4 / value4
  • field4 / value4
  • 5 / value5
  • field5 / value5

From what I understand

A while loop would allow me to go through each row from the database.

A foreach loop is similar to a while loop, but instead of going through database entries, it goes through the key/value pairs from an array.

(Please feel free to correct me if I am wrong about these previous statements.)

Thinking outloud

I'm starting to wonder, as I write this question, if the while and foreach seem kind of redundant in that both seem would parse the values, probably causing my duplicates...?

行号(在这种情况下1)不是一个键吗?

小智.. 8

默认情况下,mysqli_fetch_array()返回一个Associative Array($key => $value)和一个Numeric Array(0 => value),这就是你得到重复项的原因 - 一些条目的列名是键,其他条目有一个数字索引.

如果你想要一个关联数组,你可以使用:

 mysqli_fetch_array($q, MYSQLI_ASSOC);
 //or
 mysqli_fetch_assoc($q);

或者对于数字数组:

 mysqli_fetch_array($q, MYSQLI_NUM);
 //or
 mysqli_fetch_row($q);

欲了解更多信息:http://www.php.net/manual/en/mysqli-result.fetch-array.php

1 个回答
  • 默认情况下,mysqli_fetch_array()返回一个Associative Array($key => $value)和一个Numeric Array(0 => value),这就是你得到重复项的原因 - 一些条目的列名是键,其他条目有一个数字索引.

    如果你想要一个关联数组,你可以使用:

     mysqli_fetch_array($q, MYSQLI_ASSOC);
     //or
     mysqli_fetch_assoc($q);
    

    或者对于数字数组:

     mysqli_fetch_array($q, MYSQLI_NUM);
     //or
     mysqli_fetch_row($q);
    

    欲了解更多信息:http://www.php.net/manual/en/mysqli-result.fetch-array.php

    2023-02-09 15:44 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有