Difference b/w Mysql Fetch Row,Object,Assoc and Array

Many of the Php programming newbies get confused about mysql_fetch_row(), mysql_fetch_object(), mysql_fetch_assoc(), mysql_fetch_array() functions.

Any Difference between mysql_fetch_row(), mysql_fetch_object(), mysql_fetch_assoc(), mysql_fetch_array() functions ?.

Basically all of these functions performs with a similar process.For example.

Let us create a table “Table1″ with clear example with three fields “id”,”username”,”password”.

Table:Table1

Insert a new row in to the table with values 1 for id,Spiral for username and Spiral123 for password.

Id Username Password
1 Spiral Spiral123

Database.php

<?php
$query=mysql_connect("localhost","root","");
mysql_select_db("table1",$query);
?>

mysql_fetch_row()

Fetch result row as an numeric way.This function will return a row where the values will come in the order as they are defined in the SQL query, and the keys will span from 0 to one less than the number of columns selected.

include(‘database.php’); $query=mysql_query(“select * from table1”); $row=mysql_fetch_row($query); echo $row[0]; echo $row[1]; echo $row[2]; ?>

Result

1 Spiral Spiral123

mysql_fetch_assoc()

Fetch a result row as an associative array.This function will return a row as an associative array where the column names will be the keys storing corresponding value.

<?php
include('db.php'); 
$query=mysql_query("select * from table1"); 
$row=mysql_fetch_assoc($query); 
echo $row['id']; 
echo $row['username']; 
echo $row['password']; 
?>

 

Result

1 Spiral Spiral123

mysql_fetch_array()

Fetch a result row as an associative array, a numeric array and also it fetches by both associative & numeric array.This function will actually return an array with both the contents of mysql_fetch_rowand mysql_fetch_assoc merged into one. It will both have numeric and string keys which will let you access your data in whatever way you’d find easiest.

<?php
include('db.php'); 
$query=mysql_query("select * from table1"); 
$row=mysql_fetch_array($query); 
echo $row['id']; 
echo $row['username']; 
echo $row['password'];
?>

/* here both associative array and numeric array will work. */

echo $row[0];

echo $row[1];

echo $row[2];

?>

Result

1 Spiral Spiral123

mysql_fetch_object()

Fetch a result row as an object

<?php
include('db.php'); 
$query=mysql_query("select * from table1"); 
$row=mysql_fetch_object($query); 
echo $row->id; 
echo $row->username; 
echo $row->password; ?>

Result

1 Spiral Spiral123

Please follow and like us:



Leave a Comment

Your email address will not be published. Required fields are marked *