Mysqli fetch_assoc第一个结果


Mysqli fetch_assoc first result

我有一个fetch_assoc查询,它将获取14行,但我希望显示FIRST结果,使其与其他结果不同,然后其他结果都很普通。

    $site_events = $db->query("SELECT * FROM site_events ORDER BY time ASC limit 14");
        while($events = $site_events->fetch_assoc()) {
        if( first result???? ) { //this is where im stuck
           echo $events['title'], 'FIRST RESULT';
        }
        //then display others like a normal list..
        echo $events['title'], '<br />';
   }

我基于Yatin Trivedi的答案,但用一个我未设置的变量删除了增量。你不会注意到区别,但这要快一点。这是因为$i++不必每次调用。此外,unset()真的很快。编辑:这个答案从$i=0$i++开始,现在不再是了:)

$hasNotLooped = true; // set it before you run the loop
$site_events = $db->query("SELECT * FROM site_events ORDER BY time ASC limit 14");
    while($events = $site_events->fetch_assoc()) {
    if( $hasNotLooped ) {
       echo $events['title'], 'FIRST RESULT';
       unset($hasNotLooped);
    }
    //then display others like a normal list..
    echo $events['title'], '<br />';
}

您可以获取"while"之外的第一行,然后正常继续。但首先你可能应该检查是否有数据选择以防万一:

$site_events = $db->query("SELECT * FROM site_events ORDER BY time ASC limit 14");
if($db->field_count){
   $event = $site_events->fetch_assoc();
   echo $event['title'], 'FIRST RESULT';
   while($events = $site_events->fetch_assoc()) {
     //then display others like a normal list..
     echo $events['title'], '<br />';
   }
}
$tmp=true;
$site_events = $db->query("SELECT * FROM site_events ORDER BY time ASC limit 14");
    while($events = $site_events->fetch_assoc()) {
    if( $tmp) { //this is where im stuck
       echo $events['title'], 'FIRST RESULT';
       $tmp=false;
    }
    else
    {
    //then display others like a normal list..
    echo $events['title'], '<br />';
    }
}