如何在MySQL查询结果中找到特定行? [英] How to find specific row in MySQL query result?

查看:41
本文介绍了如何在MySQL查询结果中找到特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我这样做是为了检索我的整个表格:

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

然后,在我的 PHP 页面的另一部分,我执行另一个查询(针对特定行):

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

所以,我正在执行两个查询.但是,我真的不必那样做,不是吗?我的意思是,我在第二个查询中检索的行已经存在于 $result(我的第一个查询的结果)中,因为它包含我的整个表.

因此,我想直接从 $result 中提取所需的行,而不是执行第二个查询(同时保持 $result 本身的完整性).

我该怎么做?

<小时>

好的,这就是我实现它的方式:

function getRowById ( $result, $id ){while ( $row = mysql_fetch_array( $result ) ) {如果 ( $row['id'] == $id ) {mysql_data_seek( $result, 0 );返回 $row;}}}

解决方案

可以在结果集中循环查找行,然后将内部指针重置回第一行:

while($row = mysql_fetch_array( $result)){if($row['id'] == $id){//找到行,进行处理...//重置指针并中断循环if(!mysql_data_seek($result, 0))//处理错误休息;}}

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;
        }
    }
}

解决方案

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;
  }
}

这篇关于如何在MySQL查询结果中找到特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆