<?Php
require "config.php"; // Database connection string
$count=$dbo->prepare("select * from pdo_admin ");
$count->execute();
echo "Number of Columns : ". $count->columnCount();
?>
The output will be
Number of Columns : 5
Query can be changed like this
$count=$dbo->prepare("select id,userid from pdo_admin ");
The output will be
Number of Columns : 2
This example demonstrates how to use PDO::columnCount() after executing a SELECT query.
$stmt = $pdo->query("SELECT name, age, gender FROM users");
$columnCount = $stmt->columnCount();
echo "Number of columns: " . $columnCount;
Output:
Number of columns: 3
This example shows how the number of columns varies based on the SQL query.
$stmt = $pdo->query("SELECT * FROM users WHERE age > 18");
$columnCount = $stmt->columnCount();
echo "Column count for this query: " . $columnCount;
Output:
Column count for this query: 5
Use columnCount() to fetch column names dynamically after a query.
$stmt = $pdo->query("SELECT * FROM users");
$columnCount = $stmt->columnCount();
for ($i = 0; $i < $columnCount; $i++) {
$colMeta = $stmt->getColumnMeta($i);
echo "Column name: " . $colMeta['name'] . "<br>";
}
Output:
Column name: id
Column name: name
Column name: age
Column name: gender