dqfsbvd43312 2012-04-15 16:51 采纳率: 0%
浏览 212
已采纳

如何在MySQL查询结果中找到特定的行?

So I do this to retrieve my entire table:

$result = mysql_query( 'SELECT * FROM mytable' );

Then, in another part of my PHP-page, I do another query (for a specific row):

$result2 = mysql_query( 'SELECT * FROM mytable WHERE id = ' . $id );
$row = mysql_fetch_array( $result2 );

So, I'm performing two querys. However, I don't really have to do that, do I? I mean, the row that I'm retrieving in my second query already is present in $result (the result of my first query), since it contains my entire table.

Therefore, instead of doing the second query, I would like to extract the desired row from $result directly (while keeping $result itself in tact).

How would I do that?


OK, so this is how I've implemented it:

function getRowById ( $result, $id )
{
    while ( $row = mysql_fetch_array( $result ) ) {
        if ( $row['id'] == $id ) {
            mysql_data_seek( $result, 0 );
            return $row;
        }
    }
}
  • 写回答

3条回答 默认 最新

  • doucong1268 2012-04-15 17:00
    关注

    You can loop through the result set to find the row, and then reset the internal pointer back to the first row:

    while($row = mysql_fetch_array( $result))
    {
      if($row['id'] == $id)
      {
        //row found, do processing ...
        //reset pointer and break from loop
        if(!mysql_data_seek($result, 0))
          //handle error
        break;
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 类图中关联与聚合的区别
  • ¥15 ENVI高分五号去除云层的方法
  • ¥15 16进制数据如何得到奇偶校验位
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题
  • ¥15 海湾GST-DJ-N500
  • ¥15 氧化掩蔽层与注入条件关系