PHP MySQL PDO Fetch INTO
From w3cyberlearnings
Contents |
PHP PDO::FETCH_INTO
PDO:FETCH_INTO allows us to fetch data into an existing instance of a class directly. It is similar to the PDO::FETCH_CLASS, as the field names are mapped directly to the class property. PDO::FETCH_INTO can fetch into public property only.
Syntax PDO::FETCH_INTO
// class class user { public $id; public $first_name; public $last_name; public $email; public function sendEmail($message) { echo $message . ' send to ' . $this->email; } public function sayHi($message) { echo 'Hello ' . $this->first_name . ' ' . $this->last_name . '<br/>'; echo $message; echo '<br/>'; } } db = new PDO($dns, $user, $pass); $sql = "SELECT id, first_name, last_name, email FROM user_infor"; $sq = $db->query($sql, PDO::FETCH_INTO, new user());
Example 1
<?php // class class user { public $id; public $first_name; public $last_name; public $email; public function sendEmail($message) { echo $message . ' send to ' . $this->email; } public function sayHi($message) { echo 'Hello ' . $this->first_name . ' ' . $this->last_name . '<br/>'; echo $message; echo '<br/>'; } } // end class $dns = 'mysql:host=localhost;dbname=w3cyberlearning'; $user = 'user2000'; $pass = 'password2000'; $db = new PDO($dns, $user, $pass); $sql = "SELECT id, first_name, last_name, email FROM user_infor"; $sq = $db->query($sql, PDO::FETCH_INTO, new user()); while ($row = $sq->fetch()) { echo 'id: ' . $row->id . '<br/>'; echo $row->sayHi('Good Morning'); } ?>
Output
id: 1 Hello bob lema Good Morning id: 2 Hello Alex Gate Good Morning id: 3 Hello George Washington Good Morning