如何在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;
        }
    }
}

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

After the first query cache the data:

$rows = array();
while($row=mysql_fetch_array($result) {
    $rows[$row[0]] = $row;
}

Then simply access the data using:

$row = $rows[$id];

id needs to be the first column in your field for this to work.

Assuming you do it in the order you specify here, and you already know the id you want to find the first time you do the iteration, you can just save the value from there.

So, somewhere in your script you do something like

while ( $row = mysql_fetch_array( $result ) ) {
    // process data
}

In that loop, you could just check for your id and save it for later.

while ( $row = mysql_fetch_array( $result ) ) {
        // process data
        if ($row['id'] == $id) $importantid = $row;
    }

This would be the fastest approach if you only need to get one row out, since you'll only have to iterate over $result once.