Skip to content

Instantly share code, notes, and snippets.

@eskayamadeus
Created May 13, 2021 12:51
Show Gist options
  • Save eskayamadeus/63e021721ced90ad13fafa671949259f to your computer and use it in GitHub Desktop.
Save eskayamadeus/63e021721ced90ad13fafa671949259f to your computer and use it in GitHub Desktop.
A brief description of various ways one can fetch data in PHP using PDO
<?php
include_once('../../db.php');
// SET 1
$sql = 'SELECT * FROM users';
$stmt = $userConn->query($sql);
$users = $stmt->fetch(); // by default, the argument in the bracket is PDO:FETCH_BOTH
echo '<pre>',print_r($users),'</pre>';
// =============================================
// SET 2 (fetch as numeric array)
$sql = 'SELECT * FROM users';
$stmt = $userConn->query($sql);
$users = $stmt->fetch(PDO::FETCH_NUM);
echo '<pre>',print_r($users),'</pre>';
// =============================================
// SET 3 (fetch as assoociative array)
$sql = 'SELECT * FROM users';
$stmt = $userConn->query($sql);
$users = $stmt->fetch(PDO::FETCH_ASSOC);
echo '<pre>',print_r($users),'</pre>';
// =============================================
// SET 4 (fetch as anonymous object)
$sql = 'SELECT * FROM users';
$stmt = $userConn->query($sql);
// either
$users = $stmt->fetch(PDO::FETCH_OBJ);
echo '<pre>',print_r($users),'</pre>';
// or
/* while($users = $stmt->fetch(PDO::FETCH_OBJ)) {
echo $users->username, '<br>';
} */
// =============================================
// SET 5 (fetch using Class)
class UserRecord {
public $email, $username, $entry;
public function __construct()
{
$this->entry = "{$this->username} has email: {$this->email}";
}
}
$sql = 'SELECT * FROM users';
$stmt = $userConn->query($sql);
$stmt->setFetchMode(PDO::FETCH_CLASS, 'UserRecord');
while($users = $stmt->fetch()){
echo $users->entry.'<br>';
}
// =============================================
// SET 6 (fetch all as assoociative arrays)
$sql = 'SELECT * FROM users';
$stmt = $userConn->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>',print_r($users),'</pre>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment