mysql query skips first row

时间:2016-04-04 16:49:15

标签: php mysql

$sqlList ="select title from podcast order by date_pd desc limit 5";
$rslt2 = mysqli_query($conn, $sqlList) or die ("Fail".mysqli_error($conn));         
$record2 = mysqli_fetch_array($rslt2);          
$nRows = mysqli_num_rows($rslt2);
for ($i=0; $i<$nRows; $i++) {
        $record2 = mysqli_fetch_array($rslt2);  
        echo $record2["title"];
}           

the echo result is skipping the first row of the query, what am I doing wrong?

2 个答案:

答案 0 :(得分:2)

You are loosing the first row of your result set because you read the first row and throw it ways/ignore it

$sqlList ="select title from podcast order by date_pd desc limit 5";
$rslt2 = mysqli_query($conn, $sqlList) or die ("Fail".mysqli_error($conn));         

// this line gets the first row of your result set 
// and you just ignore it therefore throw it away
$record2 = mysqli_fetch_array($rslt2);          

$nRows = mysqli_num_rows($rslt2);

for ($i=0; $i<$nRows; $i++) {
        $record2 = mysqli_fetch_array($rslt2);  
        echo $record2["title"];
}           

As @Anant says, you are better advised to use a while as if the result set is empty, it just does nothing. Admittedly not always an advantage.

$sqlList ="select title from podcast order by date_pd desc limit 5";
$rslt2 = mysqli_query($conn, $sqlList) or die ("Fail".mysqli_error($conn));         

while ( $record2 = mysqli_fetch_array($rslt2) ) {
        echo $record2["title"];
}           

答案 1 :(得分:1)

remove the line $record2 = mysqli_fetch_array($rslt2);, which is placed before the for loop.

new code would be:

$sqlList ="select title from podcast order by date_pd desc limit 5";
$rslt2 = mysqli_query($conn, $sqlList) or die("Fail".mysqli_error($conn));                 
$nRows = mysqli_num_rows($rslt2);
for ($i=0; $i<$nRows; $i++) {
    $record2 = mysqli_fetch_array($rslt2);  
    echo $record2["title"];
}