【问题标题】:Mysqli fetch_assoc first resultMysqli fetch_assoc 第一个结果
【发布时间】:2013-11-27 16:18:28
【问题描述】:

我有一个 fetch_assoc 查询,它将抓取 14 行,但我希望显示第一个结果,以便它与其他结果不同,然后其余的只是普通的。

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

【问题讨论】:

  • 你总是可以使用一个变量来存储状态

标签: php mysql mysqli


【解决方案1】:

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

【讨论】:

  • 为什么不只是if ($hasNotLooped) $hasNotLooped = false;
  • 我猜这并不重要...任何一种方式都有优势。你可以说我刚刚从内存中删除了一些信息
  • 是否有可能使第一个结果再次重复?导致它的重复和回声像正常的一样。
  • else{}包装它
【解决方案2】:

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

【讨论】:

    【解决方案3】:
    $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 />';
        }
    }
    

    【讨论】:

    • 布尔值比整数更快。只是说。
    • 您可以通过在 if 语句中添加 $tmp++ 来提高速度...(微观差异:))
    • 是否有可能使第一个结果再次重复?导致它的重复和回声像正常的一样。
    猜你喜欢
    • 2015-09-28
    • 2013-03-06
    • 2010-11-07
    • 2018-10-03
    • 2021-12-26
    • 1970-01-01
    • 2013-05-19
    • 2017-02-17
    相关资源
    最近更新 更多