How would I count the columns of a custom WPDB query?

This does work although I need a different kind of output:

$sql_assoc = "SELECT * FROM test";
$num_cols  = count((array) current($sql_assoc));

echo $num_cols;


But what I would want is every column+the total as output, like so:


Usually you'd accomplish this by doing the following but of course this won't work in wordpress or at least I have no idea how to use field_count in wordpress since outputting query results of a custom WPDB goes differently like so in PHP:

 $sql = "SELECT * FROM test"
 if($result = $mysqli->query($sql))
        $numcol = $mysqli->field_count;

Under straight mysql core functions you would use mysql_num_fields, but through $wpdb (wordpress database object), I found the following worked for me.

    $result = $wpdb->get_results('DESCRIBE '.$table,ARRAY_A);
    $columns = array();
    foreach($result as $row) {
        $columns[] = $row['Field'];
    $num_fields = count($columns);

This is not possible.

I instead created functions to execute count queries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.