How to find specific row in MySQL query result?
- by Šime Vidas
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;
}
}
}