Here is a simple mysqli based class. This method will also work in empty tables. Of course, add your own error checking as needed.
Success will return the numeric index of the column names from table $.
Failure or non-string input will return FALSE .
class mysqlz extends mysqli { function fetch_table_columns($table) { if(!is_string($table)) { return false; } elseif($obj = $this->query("SHOW COLUMNS FROM " . $table)) { while($fields = $obj->fetch_object()) { $columns[] = $fields->Field; } return $columns; } else { return false; } } }
To use, first create your database as usual:
$mysql = new mysqlz($host, $user, $pass, $database);
Then call the method to get the column names:
$columns = $mysql->fetch_table_columns("table_name_here");
Depending on your table, the resulting array should look like this: var_dump () :
array (3) {[0] => string (2) "id" [1] => string (10) "first_name" [2] => string (9) "last_name"}
If the method returns false (var_dump returns bool(false) ), you can check the current error with $mysqlz->error . For more information on error checking, check out the mysqli PHP manual at http://www.php.net/manual/en/book.mysqli.php .
source share