php PDO fetch_obj code example
Example 1: PDO::FETCH_OBJ
It should be mentioned that this method can set even non-public properties. It may sound strange but it can actually be very useful when creating an object based on mysql result.
Consider a User class:
<?php
class User {
private $id, $name;
private function __construct () {}
public static function load_by_id ($id) {
$stmt = $pdo->prepare('SELECT id, name FROM users WHERE id=?');
$stmt->execute([$id]);
return $stmt->fetchObject(__CLASS__);
}
}
$user = User::load_by_id(1);
var_dump($user);
?>
fetchObject() doesn't care about properties being public or not. It just passes the result to the object. Output is like:
object(User)#3 (2) {
["id":"User":private]=>
string(1) "1"
["name":"User":private]=>
string(10) "John Smith"
}
Example 2: how to fetch data using pdo in php
<?php
require_once 'dbconfig.php';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = 'SELECT lastname,
firstname,
jobtitle
FROM employees
ORDER BY lastname';
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Query Data Demo</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div id="container">
<h1>Employees</h1>
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
</tr>
</thead>
<tbody>
<?php while ($row = $q->fetch()): ?>
<tr>
<td><?php echo htmlspecialchars($row['lastname']) ?></td>
<td><?php echo htmlspecialchars($row['firstname']); ?></td>
<td><?php echo htmlspecialchars($row['jobtitle']); ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</body>
</div>
</html>