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 ) )
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.