douhui3305 2015-04-19 20:10
浏览 47

是否有任何方法可以从查询结果pre-While循环中获取第一个结果?

My site has a sizable table generated by a mysqli_query; the query includes a column 'messagetime':

$result = mysqli_query($cxn, 
"
  SELECT ......., messagetime
  FROM messages 
  ORDER by messagetime 
  DESC
"
);

I then generate the table (in php) with the help of a while loop:

echo "<table id='myTbl' class='newest' border='1'>";
echo "<th>Content</th> //etc.
echo "<tbody>";

while ($row = mysqli_fetch_assoc($result)) {

    // Fill the table body here

}

echo "</tbody></table>";

Nothing earth-shaking. However, the site uses polling to refresh the table, and I need to store the messagetime of the first result of the query in the table, like this:

echo "<table id='myTbl' class='newest".$newestTime."' border='1'>";

Right now, to capture the first (newest) messagetime, I am tweaking my While loop to do this:

$i = 0;
while ($row = mysqli_fetch_assoc($result)) {

     if ($i == 0) {
         echo "<table id='myTbl' class='newest".$row['messagetime']."' border='1'>";
         echo "<th>Content</th> //etc.
         echo "<tbody>";
     }

    // Fill the table here

     $i++;
}

echo "</tbody></table>";

However, this seems kind of hacky to me. Is there any way, without a subquery or union (since my query is actually the product of 2 joins, and is already expensive; this approach was described here), to simply pluck the first result from the query somehow, something like this?

$result = mysqli_query($cxn, 
"
  SELECT ......., messagetime, **first_messagetime_result AS newest_time**
  FROM messages 
  ORDER by messagetime 
  DESC
"
);

Thanks for any insight!

  • 写回答

2条回答 默认 最新

  • dslfq06464 2015-04-19 20:33
    关注
    if ($result->num_rows > 0) {
        $row = mysqli_fetch_assoc($result)
        echo "<table id='myTbl' class='newest".$row['messagetime']."' border='1'>";
        echo "<thead><tr>";
        echo "<th>Content</th>"; //etc.
        echo "</tr></thead>";
        echo "<tbody>";
        do {
            // Fill the table here
        } while ($row = mysqli_fetch_assoc($result));
        echo "</tbody></table>";
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大