Difference between mysql_fetch_row, mysql_fetch_assoc,mysql_fetch_array & mysql_fetch_object ?
Note: for new version of PHP, below mysql should be replaced by mysqli in function names
1. mysql_fetch_row — Get a result row as an enumerated array
$rows = mysql_fetch_row( "select name, address from people");
Means you then get each of the row results as a straight array
foreach( $rows as $row )
echo $row[0] . ' lives at ' . $row[1] ;
Means you then get each of the row results as a straight array
foreach( $rows as $row )
echo $row[0] . ' lives at ' . $row[1] ;
2. mysql_fetch_assoc — Fetch a result row as an associative array
$rows = mysql_fetch_assoc( "select name, address from people" );
Means you then get each of the row results as a named array elements, an associative array.
foreach( $rows as $row )
echo $row['name'] . ' lives at ' . $row['address'];
Means you then get each of the row results as a named array elements, an associative array.
foreach( $rows as $row )
echo $row['name'] . ' lives at ' . $row['address'];
3. mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
3A For a numeric array$rows = mysql_fetch_array( "select name, address from people");
foreach( $rows as $row )
echo $row[0] . ' lives at ' . $row[1] ;
3B For associate array
Example3 suppose we have posts table with column id, title and text as follows:$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 10"; $result = mysql_query($query);
$posts = array(); while ($row = mysql_fetch_array($result)) { $posts[] = array( 'id' => $row['id'], 'title' => $row['title'], 'text' => $row['text'] ); //equal to
$posts[] = $row;
}
foreach( $posts as $row1 ) { echo $row1['title']; }
4. mysql_fetch_object — Fetch a result row as an object
$rows = mysql_fetch_object( "select name, address from people" );
Means you then get each of the row results using the object notation.
foreach( $rows as $row )
echo $row->name . ' lives at ' . $row->address ;
Reference for The Difference Between mysql_fetch_array() And mysql_fetch_assoc(:
http://deepbluespaces.blogspot.ca/2008/05/difference-between-mysqlfetcharray-and.html
No comments:
Post a Comment