How to fetch data from a database using different fetch styles in PDO in PHP?

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:

  1. Default fetch style (PDO::FETCH_BOTH):
    • This is the default fetch style.
    • It returns an array indexed by both column name and 0-indexed column number.
    • Example usage:
$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"; }
  1. Fetch style - PDO::FETCH_ASSOC:
    • It returns an associative array indexed by column name.
    • Example usage:
$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"; }
  1. Fetch style - PDO::FETCH_NUM:
    • It returns an array indexed by 0-indexed column number.
    • Example usage:
$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"; }
  1. Fetch style - PDO::FETCH_OBJ:
    • It returns an anonymous object with property names that correspond to the column names.
    • Example usage:
$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.