PDO Fetch Class


 

PDO Fetch Class

In this tutorial we will study about PDO Fetch Class method in PHP, how to access MySQL using PDO Fetch Class method , How to retrieve data etc. Examples will make this clearer.

In this tutorial we will study about PDO Fetch Class method in PHP, how to access MySQL using PDO Fetch Class method , How to retrieve data etc. Examples will make this clearer.

PDO Fetch Class:

Using PDO::FETCH_CLASS we can map the fields of a table as properties (fields/variables) of a class. With the help of this method we can achieve greater speed because the mapping activity is done internally. As illustrated in the following example we can see that we have declared a class and a method called first_cap (which is used to change  the first alphabet in capital form ) and in the following part an object is declared as the object of this class and by calling this method we can change the first alphabet of the field last_name, you can use any other method, field.

Example:

<?php

class employee

{

public function first_cap()

{

return ucwords($this->emp_last_name);

}

}

$host='localhost';

$user='root';

$pass='';

try{

$dbh=new PDO("mysql:host=$host;dbname=ajax",$user,$pass);

echo "connected<br/>";

$sql="select * from emp_details";

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

$obj=$stmt->fetchALL(PDO::FETCH_CLASS,'employee');

foreach($obj as $emp){

echo $emp->first_cap()."<br/>"; }

$dbh=null;

}

catch(PDOException $e)

{

echo $e->getMessage();

}

?>

Output:

0

connected
Tendulkar
Dravid
Ganguly

Ads