Wednesday, 13 June 2012

Difference between mysql_fetch_array,mysql_fetch_row and mysql_fetch_object

mysql_fetch_row ::Return row as aan enumrated array and each line contain a unique ID .example.
$result=mysql_query($query);
while($row=mysql_fetch_row($result))
{
print "$row[0]";
print "$row[1]";
print "$row[2]";
}

mysql_fetch_array ::Return row as anassociative or anenumrated arrayor both which is default .you can refer to outputs as databases fieldname rather then number.example.
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
print "$row['name']";
print "$row['address']";
print "$row['city']";
}

mysql_fetch_object :: it return as an object on the place of array.

$result=mysql_query($query);
while($row=mysql_fetch_object($result))
{
print "$row->name";
print "$row->address";
print "$row->city";
}


Explained:


mysql_fetch_array:
--> it returns array as index as table field name as well as it's index number
from table student you fetch record like this:
while($res=mysql_fetch_array($rs)){

    echo  $res['id'] ;// print id value
        or
    echo $res[0];// same as above statement
 
   

}

mysql_fetch_row:
--> it returns array as  it's index number
from table student you fetch record like this:
while($res=mysql_fetch_row($rs)){

 
    echo $res[0];// it can fetch value by index value not table field name
 
   

}



mysql_fetch_object
--> it returns array as  it's as object as table field name
from table student you fetch record like this:
while($res=mysql_fetch_object($rs)){

 
    echo $res->id;//  it can fetch value by object value not table field name or it's                                     //index
 
   

}


In order to for you to know which to use you'll need to know what each of the above returns.

mysql_fetch_assoc - returns an associative array of your field names eg $row['field_name_here']

mysql_fetch_row - returns a numeric array eg $row[0] returns the first column, $row[1] returns the second column etc.

However mysql_fetch_array retuns both an associative and numeric array.

I personally use mysql_fetch_assoc or mysql_fetch_array.

No comments:

Post a Comment