Share on Google+Share on Google+

PDO Fetch Into

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

PDO Fetch Into:

Like in the previous tutorial, we will deal with OOP concept in this tutorial. In PHP PDO::FETCH_INTO is a constant which allows us to fetch the data from an existing database into an instance or object of a class. Like the previous tutorial (based on class) PDO::FETCH_CLASS the fields were mapped to the class fields.  Keeping this in mind, we would make the duplicate of PDO::FETCH_CLASS by creating an object of the class. In the following example we use getter (__get) method and setter (__set) method.

Example:

<?php

class Test

{

protected $cols;

function __set($name, $value) {

$this->cols[$name] = $value;

}

function __get($name) {

return $this->cols[$name];

}

}

$host='localhost';

$db='ajax';

$user='root';

$pass='password';

$obj = new Test();

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

$stmt = $db->prepare("select * from emp_details");

$stmt->setFetchMode(PDO::FETCH_INTO, $obj);

$stmt->execute();

foreach ($stmt as $a) {

print_r($a);

}

?>

 

Output:

Test Object ( [cols:protected] => Array ( [emp_first_name] => sachin [emp_last_name] => tendulkar [emp_city] => mumbai ) ) Test Object ( [cols:protected] => Array ( [emp_first_name] => rahul [emp_last_name] => dravid [emp_city] => bangalore ) ) Test Object ( [cols:protected] => Array ( [emp_first_name] => sourav [emp_last_name] => ganguly [emp_city] => kolkata ) )

Advertisements

Posted on: April 6, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.