columncount : Number of Columns Present in the query

PHP PDO & MYsQL By using PDO MySQL function columncount() we can get number of columns present in the query.

Here is the code to get total field numbers present in the table
<?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

Example 1: Using PDO::columnCount() After a SELECT Query

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

Example 2: Checking Column Count for Different Queries

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

Example 3: Fetching Column Names Dynamically

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

PDO References rowcount()


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer