PDO (PHP Data Objects) is a PHP extension that provides a consistent interface for accessing databases. It supports various fetch styles to retrieve data from a database. Here's how you can use different fetch styles in PDO:
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
// Fetch data using default fetch style
while ($row = $stmt->fetch()) {
echo $row['column_name'] . ' - ' . $row[0] . "\n";
}
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
// Fetch data using associative fetch style
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['column_name'] . "\n";
}
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
// Fetch data using numeric fetch style
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
echo $row[0] . "\n";
}
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
// Fetch data using object fetch style
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
echo $row->column_name . "\n";
}
These are some of the commonly used fetch styles in PDO to retrieve data from a database. You can choose the fetch style that best suits your needs.