How to find specific row in MySQL query result?
Posted
by
Šime Vidas
on Stack Overflow
See other posts from Stack Overflow
or by Šime Vidas
Published on 2012-04-15T16:51:15Z
Indexed on
2012/04/15
17:29 UTC
Read the original article
Hit count: 202
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;
}
}
}
© Stack Overflow or respective owner