Jump to: navigation, search

PHP MySQL PDO Fetch Object

From w3cyberlearnings

Contents

PHP PDO Fetch Records AS Object

Fetch records as object.

Syntax PDO

$sq = $db->query("SELECT 
     id,
     first_name, 
     last_name,
     email 
     FROM user_infor");

$r = $sq->fetch(PDO::FETCH_OBJ);

Example 1

<?php
// fetch as object
$dns = 'mysql:host=localhost;dbname=w3cyberlearning';
$user = 'user2000';
$pass = 'password2000';

$db = new PDO($dns, $user, $pass);

$sq = $db->query("SELECT 
id,
first_name, 
last_name,
email FROM user_infor");

echo '<table border="1">';
echo '<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>';

while ($r = $sq->fetch(PDO::FETCH_OBJ)) {
 echo '<tr>';
 echo '<td>' . $r->id . '</td>';
 echo '<td>' . $r->first_name . '</td>';
 echo '<td>' . $r->last_name . '</td>';
 echo '<td>' . $r->email . '</td>';
 echo '</tr>';
}
echo '</table>';
?>

Output

Php mysql pdo fetch 1.png


Related Links


Navigation
Web
SQL
MISC
References