PDO Fetch Object


 

PDO Fetch Object

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.

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

0

$user='root';

$password='';

try

1

{

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

$sql="select * from student";

2

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

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

print_r($obj);

3

var_dump($obj);

$dbh=null;

}

4

catch(PDOException $c)

{

echo $c->getMessage();

5

}

?>

 

6

Output:

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

Ads