Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

php - Retrieve all row but the first record is missing

$query = "SELECT * FROM abc";

    if ($result = $db->query($query)) {

      $row = $result->fetch_assoc();


        while ($row = $result->fetch_assoc()) {

            $data[] = array("a"=>$row["a"], 
                            "b"=>$row["b"],
                            "c"=>$row["c"],
                            "d"=>$row["d"]
                            ); 


        }

        $result->close();
    }

$db->close();

        <?php foreach ($data as $row) { ?>

                <form action="">
                    <div class="col-lg-3">
                        <input type="text" value="<?php echo $row['a'] ?>"/>
                    </div>
                    <div class="col-lg-3">
                        <input type="text" value="<?php echo $row['b'] ?>"/>
                    </div>
                    <div class="col-lg-3">
                        <input type="text" value="<?php echo $row['c'] ?>"/>
                    </div>
                    <div class="col-lg-3">
                        <input type="text" value="<?php echo $row['d'] ?>"/>
                    </div>
                </form>

              <?php } ?>

Above is the exact code that I used to retrieve all the row in a table. The strange part is that I have 5 row and it only show 4. The first row is missing. I wonder why.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your code, you're calling $row = $result->fetch_assoc(); just before starting your while loop. This line is "consuming" your first raw and when you're entering in the loop, you move the cursor to the second row by calling this same method a second time.

The condition of the while loop is executed BEFORE the content, here you'll find more info about PHP While loop

To fix your code, remove this first line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...