What is the difference between fetchColumn() and fetch() in PHP when retrieving data from a database?
When retrieving data from a database in PHP using PDO, fetchColumn() is used to retrieve a single column value from the next row of a result set, while fetch() is used to fetch the next row from a result set as an associative array or object. If you only need a specific column value, fetchColumn() is more efficient as it directly returns the value without the need to iterate through the entire row data. On the other hand, fetch() is useful when you need to access multiple columns of a row.
// Using fetchColumn() to retrieve a single column value
$stmt = $pdo->query("SELECT name FROM users WHERE id = 1");
$name = $stmt->fetchColumn();
echo $name;
// Using fetch() to retrieve a row as an associative array
$stmt = $pdo->query("SELECT * FROM users WHERE id = 1");
$user = $stmt->fetch(PDO::FETCH_ASSOC);
echo $user['name'];