Test if table field exists..

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Test if table field exists..

Post by Benjamin »

What would be the best way to test a table for a field. I need to check whether or not certain fields exists.

Just run a test query and catch the error?

Would this be something suited for the try and catch functions?
jamiel
Forum Contributor
Posts: 276
Joined: Wed Feb 22, 2006 5:17 am
Location: London, United Kingdom

Post by jamiel »

You could do this ...

Code: Select all

function colExists($colName)
{
    $sql = "DESCRIBE `table_name`;";

    $result = mysql_query($sql);

    while ($row = mysql_fetch_assoc($result)) {
        if ($colName == $row['Field'])
            return true;
    }
}
Better ways to write it but you get the idea.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Cool thanks, I used my database class :wink:

Code: Select all

$Database->query = "DESCRIBE `thisTable`";
                $Database->sendQuery();
                
                while ($Data = $Database->fetchRow) {
                    if ($_POST['FieldName'] == $Data['Field']) {
                        // field exists..
                        break;
                    }
                }
Post Reply