mysqli_fetch_array()foreach循环重复

dav*_*all 3 php mysql sql arrays foreach

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

数据库(只有1个条目)

id | field1 | field2 | field3 | field4 | field5
---|--------|--------|--------|--------|--------
1  | value1 |        | value3 | value4 | value5
Run Code Online (Sandbox Code Playgroud)

PHP源代码

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

echo "<ul>";
    while($q = mysqli_fetch_array($q))
    {
        foreach ($q as $key => $value)
        {
            if($value != NULL)
            {
                echo "<li>".$value . "</li>";

                // Line below used to show column name and corresponding value
                //echo "<li><strong>{$key}</strong> / <em>{$value}</em></li>";
            }
        }
    }
echo "</ul>";
Run Code Online (Sandbox Code Playgroud)

预期的HTML输出

<ul>
    <li>value1</li>
    <li>value3</li>
    <li>value4</li>
    <li>value5</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

电流输出

<ul>
    <li>1</li>
    <li>1</li>
    <li>value1</li>
    <li>value1</li>
    <li>value3</li>
    <li>value3</li>
    <li>value4</li>
    <li>value4</li>
    <li>value5</li>
    <li>value5</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

目前的问题

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:

<ul>
    <li>0 / 1</li>
    <li>id / 1</li>
    <li>1 / value1</li>
    <li>field1 / value1</li>
    <li>3 / value3</li>
    <li>field3 / value3</li>
    <li>4 / value4</li>
    <li>field4 / value4</li>
    <li>5 / value5</li>
    <li>field5 / value5</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

或者对于数字数组:

 mysqli_fetch_array($q, MYSQLI_NUM);
 //or
 mysqli_fetch_row($q);
Run Code Online (Sandbox Code Playgroud)

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

  • 很棒的捕获 (3认同)