2014-01-18 52 views
0

我想弄清楚爲什麼我的mysqli查詢沒有返回所有的行。出於某種原因,當數據庫中有4個結果時,它返回3個結果。它完全跳過了數據庫中的第一條記錄。這是我的查詢。MYSQLI fetch_array不工作

$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(); 
?> 
+0

在您的while循環中調用它之前調用fetch_array。這有效地損失了你的一行。 – MrVimes

+0

那麼,在'while'條件中檢索結果之前調用'$ result-> fetch_array()'。這將檢索第一行,這就是您遇到問題的原因。 – arkascha

+0

謝謝!你是對的。 – MagentoMan

回答

1

正如在評論$count = count($result->fetch_array());此表述爲將無法正常工作,使你失去了一個行(因爲它已被提取)。相反,你可以使用num_rows類似下面

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

細講,當你閱讀fetch_array()手冊,你會發現這部分

mysqli_result::fetch_array - mysqli_fetch_array - 取一結果行作爲關聯,數值數組或兩者兼有

結果行(單詞:one)將在任何時候調用此函數。因此,目前您的代碼類似於:

fetch one row -> do nothing with it 
while: 
    fetch one row -> display it