0

I am trying to figure out why my mysqli query is not returning all the rows. For some reason it returns 3 results when there are 4 in the database. It is completely skipping the first record in the database. Here is my query.

$results = "SELECT * FROM `results` LIMIT 10";
$result = $conn->query($results);
if ($result) { 
?>
    <div id="tableResults">
    <div class="row1 bg">Predicted Sex</div>
    <div class="row2 bg">Suggested Baby Boy Name</div>  
    <div class="row3 bg">Suggested Baby Girl Name</div>
    <div class="breaker"></div>

<?php
    /* fetch object array */
    $i = 0;
    $count = count($result->fetch_array());
    while ($row = $result->fetch_array()) {
?>
        <div class="row1 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['sex']; ?></div> 
        <div class="row2 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['boy_name']; ?></div>
        <div class="row3 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['girl_name']; ?></div>
<?php
    $i++;
    } 
}

$conn->close();
?>
2
  • You call fetch_array before calling it in your while loop. This effectively loses one of your rows. Commented Jan 18, 2014 at 13:19
  • Well, you call $result->fetch_array() before retrieving the result inside the while condition. That retrieves the first row which is why you run into the problem. Commented Jan 18, 2014 at 13:19

1 Answer 1

1

As was stated in the comments $count = count($result->fetch_array()); this will not work as expected and makes you lose one row (as it has been fetched). Instead you can use num_rows like the following

$count = $result->num_rows;
while ($row= $result->fetch_array()) {
    //...
}

To go into detail, when you read the manual on fetch_array(), you'll find this part

mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both

A result row (in words: one) will be fetched any time this function is called. So currently your code is similar to:

fetch one row -> do nothing with it
while:
    fetch one row -> display it
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.