SELECT count(*) FROM information_schema.`COLUMNS` C
WHERE table_name = 'your_table_name'
AND TABLE_SCHEMA = "your_db_name" TABLE_SCHEMA is required only if table name exists in more than one db
SELECT count(*) FROM information_schema.`COLUMNS` C
WHERE table_name = 'your_table_name'
AND TABLE_SCHEMA = "your_db_name" TABLE_SCHEMA is required only if table name exists in more than one db
Three practical approaches were already suggested in the thread; a few clarifications and a modern, reliable alternative are useful.
As noted, querying the schema is correct for a pure “how many columns does this table have?” check — include the database name to avoid ambiguity. The server setting that controls table-name case sensitivity can affect matches, so specifying TABLE_SCHEMA is the safer choice for scripts meant to run on different servers. ’s SHOW COLUMNS idea is fine in principle, but the sample code in Post #2 calls mysql_fetch_row() and then count() on that row — that counts columns in the metadata row (Field, Type, Null, etc.), not the number of table columns; mysql_num_rows() is the correct result-side function for that approach. Also note correctly corrected the function name in Post #4.
Avoid the old mysql_* extension: it was deprecated and removed from modern PHP. Prefer mysqli or PDO and get metadata rather than fetching all rows. Examples (safe, lightweight):
// mysqli (procedural)
$res = mysqli_query($link, "SELECT * FROM `my_table` LIMIT 0");
$columnCount = mysqli_num_fields($res);
// PDO
$stmt = $pdo->query("SELECT * FROM `my_table` LIMIT 0");
$columnCount = $stmt->columnCount(); Use LIMIT 0 (or LIMIT 1) to keep the query cheap — metadata is returned without transferring table rows. If the driver’s metadata functions are unreliable, fall back to INFORMATION_SCHEMA.COLUMNS with TABLE_SCHEMA for exact results. Finally, remember invisible/generated columns, JOINs, or a custom SELECT list all change what “number of columns” actually means for a particular query, so choose the method that matches the real need (schema introspection vs. result-set column count).
Hi,
this should help
$myQuery = "show columns from $my_table_name";
$result = mysql_query($myQuery);
$row = mysql_fetch_row($result);
$columncount = count($row); it so simple:-
$result=mysql_query("select * from table_name");
echo mysql_num_field($result);
finish....
should be:
mysql_num_fields($result);
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.