Mysqli fetch_assoc第一个结果

时间:2013-11-27 16:18:29

标签: php mysql mysqli

我有一个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 />';
   }

3 个答案:

答案 0 :(得分:2)

我基于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 />';
}

答案 1 :(得分:1)

您可以在“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 />';
   }
}

答案 2 :(得分:0)

$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 />';
    }
}