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"
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.