hello friends,

What is the difference between Mysql_fetch_object and mysql_fetch_array ?

Recommended Answers

All 4 Replies

Hi,

Might not be the best answer I can give, but I honestly believe Mysql_fetch_object returns object as in

$row->name_of_column

whereas mysql_fetch_array returns an array of data from particular query like ..

$row['name_of_column']

Although Mysql_fetch_object returns an object, it is pretty much convinient to use mysql_fetch_array in OOP. Just like this..

public function someFunction(){

$this_query = "any_thing goes here";
$this_result = mysql_query($this_query);
while ($rows = mysql_fetch_array($this_result))
{
  $res[] = $rows;
}

return $res;

}

The method above can store the output into an array, which can be then access by other methods or functions. This is crucial in passing the queried data to the template engine like Smarty or twig.

Notice that both functions are deprecated and therefore shouldn’t be used when you are programming new code. There could be a discussion comparing PDO::FETCH_ASSOC vs PDO::FETCH_OBJ and if is a good OOP practice what PHP is considering anonymous objects but that is far from what you are asking so I will not go deeper to that.

mysql_fetch_object will give back an object through which we are able to
access the database fields records although mysql_fetch_aaray
give back array of database records as well as return associative
array .

@Jkon,

Thanks for bringing that up..it is deprrecated since version 5.5.0.

So, to self-correct my response above, it should read like these...

In PDO, it has an equivalent object called FETCH_OBJ, where the column name is return as object's properties, similar to the now deprecated mysql function called Mysql_fetch_object.

$this_result = $statement->fetch(PDO::FETCH_OBJ);

## the same as above..
$this_result->Column_Name;

The same assumption can be placed on the mysql_fetch_array equivalent. The only difference is that in PDO this_result is also an object and here is why..

$this_result = $statement->fetch(PDO::FETCH_ASSOC);

## we can now iterate the object this_result

foreach($this_result as $column_name=>$values)
{
echo $column_name.' - '.$values.'<br />';
}

Still using it in OOP, the FETCH_ASSOC still make sense.. most importantly if it is for the template engine as shown by the updated example below..

public function someFunction(){

$this->query = "any_thing goes here";
$this->statement = $dbh->prepare($this->query);
$this->statement->execute();

return( $this->statement->fetch(PDO::FETCH_ASSOC));
}

The code above is a lot lighter than the codes written for the regular mysql in my previous example..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.