Home Tutorial Php Phppdo Tutorial PDO Fetch Object

 
 

Share on Google+Share on Google+
PDO Fetch Object
Posted on: April 5, 2010 at 12:00 AM
Advertisement
In this tutorial we will study about PDO Fetch Object method in PHP, how to access MySQL using PDO Fetch Object method, How to retrieve by using this method data etc. Examples will make this clearer.

PDO Fetch Object:

This is another way to access the data of a table, accessing fields as object. By using this  method we get the result set as anonymous object and this object represents the field names of the table as object properties (fields) with their respective values. This method represent  PHP  as Object Oriented.  In the following example fields of the student table are fetched as objects (anonymous/stdClass).

Example:

<?php

header('Content-type:text/plain');

$host='localhost';

$user='root';

$password='';

try

{

$dbh=new PDO("mysql:host=$hostname;dbname=db",$user,$password);

//echo "Connected to database";

$sql="select * from student";

$stmt=$dbh->query($sql);

$obj=$stmt->fetch(PDO::FETCH_OBJ);

echo $obj->name."\n";

echo $obj->roll;

$dbh=null;

}

catch(PDOException $c)

{

echo $c->getMessage();

}

?>

Output:

neeraj
2

Another way to display result can be obtained by using print_r or var_dump, as follows:

Example:

<?php

header('Content-type:text/plain');

$host='localhost';

$user='root';

$password='';

try

{

$dbh=new PDO("mysql:host=$hostname;dbname=db",$user,$password);

$sql="select * from student";

$stmt=$dbh->query($sql);

$obj=$stmt->fetch(PDO::FETCH_OBJ);

print_r($obj);

var_dump($obj);

$dbh=null;

}

catch(PDOException $c)

{

echo $c->getMessage();

}

?>

 

Output:

stdClass Object
(
    [name] => neeraj
    [roll] => 2
)
object(stdClass)#3 (2) {
  ["name"]=>
  string(6) "neeraj"
  ["roll"]=>
  string(1) "2"
}
Advertisement

Related Tags for PDO Fetch Object:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 5, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com