PHP MySQL PDO Fetch CLASS
From w3cyberlearnings
Contents |
PHP PDO FETCH_CLASS
PDO::FETCH_CLASS fetches records to class. By fetch record into class directly, we can manipulate records accordingly and return result. As the record fields will fetch into the class property.
Syntax PDO::FETCH_CLASS
// class class user { // access the record as object public function display() { echo $this->id; echo "<br/>"; echo $this->first_name; echo "<br/>"; echo $this->last_name; echo "<br/>"; echo $this->email; echo "<br/>"; } } $sql = "SELECT id, first_name, last_name, email FROM user_infor"; $sq = $db->query($sql); //$result = $sq->fetchALL(PDO::FETCH_CLASS,'user'); foreach ($sq->fetchAll(PDO::FETCH_CLASS, 'user') as $r) { $r->display(); // call the class method }
Example 1
<?php // class class user { public function display() { echo '<tr>'; echo '<td>' . $this->id . '</td>'; echo '<td>' . $this->first_name . '</td>'; echo '<td>' . $this->last_name . '</td>'; echo '<td>' . $this->email . '</td>'; echo '</tr>'; } } // 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); //$result = $sq->fetchALL(PDO::FETCH_CLASS,'user'); echo '<table border="1">'; echo '<tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Email</th></tr>'; foreach ($sq->fetchAll(PDO::FETCH_CLASS, 'user') as $r) { $r->display(); } echo '</table>'; ?>
Output
Example 2
<?php class user { public function __toString() { return sprintf("Id:%s <br/> First Name:%s <br/> Last Name:%s <br/> Email:%s <br/>", $this->id, $this->first_name, $this->last_name, $this->email); } } $db = new PDO('mysql:host=localhost;dbname=w3cyberlearning','user2000','password2000'); $sq = $db->query("SELECT * FROM user_infor", PDO::FETCH_CLASS,'user'); while($row = $sq->fetch()) { echo "$row <br/>"; } ?>