[php] PDO fetch modes

In PHP, PDO (PHP Data Objects) is a database access abstraction layer that provides a uniform method of access to multiple databases. When working with PDO, fetching data from a database is a common task and can be done in different ways. The fetch mode determines how the next row of a result set will be returned to the caller.

In PDO, there are several fetch modes that can be used with the fetch and fetchAll methods to retrieve data from the database result set. Each fetch mode has its own characteristics and is used in different scenarios.

Fetch Modes

Fetch Styles

$stmt = $pdo->prepare('SELECT name, age FROM users');
$stmt->execute();

// Fetch a row as an associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['name'];

// Fetch a row as an object
$row = $stmt->fetch(PDO::FETCH_OBJ);
echo $row->name;

Fetch Specific Class

class User {
    public $name;
    public $age;
}

$stmt = $pdo->prepare('SELECT name, age FROM users');
$stmt->setFetchMode(PDO::FETCH_CLASS, 'User');
$stmt->execute();
$user = $stmt->fetch();
echo $user->name;

Fetch Custom

function customMapping($name, $age) {
    return "Name: $name, Age: $age";
}

$stmt = $pdo->prepare('SELECT name, age FROM users');
$stmt->setFetchMode(PDO::FETCH_FUNC, 'customMapping');
$stmt->execute();
$row = $stmt->fetch();
echo $row;

Conclusion

PDO fetch modes allow PHP developers to work with database result sets in a flexible manner. By choosing the appropriate fetch mode, developers can easily retrieve and manipulate data from the database according to their specific requirements.

For more details, please refer to the PHP Manual.

By understanding the different fetch modes provided by PDO, PHP developers can effectively handle the result sets obtained from database queries in a way that best suits their individual application needs.