Link to home
Start Free TrialLog in
Avatar of Richard Korts
Richard KortsFlag for United States of America

asked on

MySQL Table Column Names

Is there a way to get the array of column names from a MySQL table?

How?
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is from an old script.  No professional would use the MySQL extension any more, but it can be mapped into the currently supported extensions by following the guidance in this article.  The query and the theory are still accurate.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

// GET THE COLUMN NAMES
$sql = "SHOW COLUMNS FROM books";
if (!$res = mysql_query($sql))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    trigger_error($errmsg, E_USER_ERROR);
}
if (mysql_num_rows($res) == 0)
{
    echo "TABLE books HAS NO COLUMNS";
}
else
{
    // MAN PAGE: http://php.net/manual/en/function.mysql-fetch-assoc.php
    while ($show_columns = mysql_fetch_assoc($res))
    {
        $my_columns[] = $show_columns["Field"];
    }
    // SEE THE COLUMN NAMES
    var_dump($my_columns);
}

Open in new window