Powered By Blogger

Saturday, 30 July 2011

Difference between mysql_fetch_assoc, mysql_fetch_row,mysql_fetch_object and mysql_fetch_array

  • mysql_fetch_array():- Fetch a result row as an associative array, a numeric array, or both by         default it fetches both.
  • mysql_fetch_row() :- Get a result row as an numeric array
  • mysql_fetch_object() :- Fetch a result row as an object
  • mysql_fetch_assoc() :- Fetch a result row as an associative array.


Suppose we have a database called 'test' and it has a table called 'members' which stores some members' information. The goal is to fetch all the members' information. Consider such code below:
$conn=mysql_connect('localhost','root','');
$mysql_select_db('test');
$rs=mysql_query('SELECT * FROM members');


Then $rs is an array that stores all personal information. You can use mysql_fetch_array() or mysql_fetch_assoc() to fetch each row by calling the function repeatedly. Consider:
while ($row=mysql_fetch_array($rs,MYSQL_NUM)){
  // ...
}

Here $row is a normal array (integer-indexed array). You cannot get data with $row['name'], $row['birthday'], etc. You must use integer as the index, e.g. $row[0], $row[1]... How to get an associative array? You need to set the second parameter of mysql_fetch_array(). MYSQL_ASSOC tells mysql_fetch_array() to return an associative array. See below:
while ($row=mysql_fetch_array($rs,MYSQL_ASSOC)){
  // ... here you can use $row['name'], $row['birthday']...
}


mysql_fetch_array($rs,MYSQL_BOTH) equals to mysql_fetch_array($rs). There's no need to use MYSQL_BOTH, so we often omit it.

So you can use two methods to fetch data by specifying the second parameter to MYSQL_BOTH or omitting the second parameter. Then both of the styles, $row[0] and $row['name'], are available.

But where's mysql_fetch_assoc()? It seems not useful. Right. mysql_fetch_assoc($rs) is equivalent to mysql_fetch_array($rs,MYSQL_ASSOC). Obviously, when you need to an associated array (string-indexed array) only, mysql_fetch_assoc() is more convenient. By the way, mysql_fetch_assoc doesn't have the second parameter. It can only return associative array so it needs less memory space to store the result array.


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

No comments:

Post a Comment