MySQL : Check if field exists

Mon, Sep 10, 2007

MySQL

Sometimes, you need to check if a field exists in a table and if it doesn’t, you need to add it to the table and ensure that its there. Below is a snippet which you can use a reference for checking whether a field/column exists in a MySQL database table.

$tableFields = mysql_list_fields("databasename", "tablename");
       
$columns = mysql_num_fields($fields);
       
for ($i = 0; $i < $columns; $i++) {
    $field_array[] = mysql_field_name($fields, $i);
}
       
if (!in_array(‘list_id’, $field_array)) {
    mysql_query("ALTER TABLE `tablename` ADD `fieldname` INT(11) NOT NULL DEFAULT ’1′;");
}

I hope that you find this useful.
The code above should give you a good idea of how to do it.

scriptlancebannerpng

This post was written by:

- who has written 71 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

7 Comments For This Post

  1. Nad Says:

    $tableFields = mysql_list_fields(“databasename”, “tablename”);

    has to be changed to

    $fields = mysql_list_fields(“databasename”, “tablename”);

  2. rubo77 Says:

    is it not possible to check this inside the mysql-statement?

    if exists tablename.fieldname ALTER TABLE `tablename` ADD `fieldname` …

    or so?

  3. Bruce Says:

    You can try this:

    IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=’table’ AND column_name=’qwerty’) BEGIN SELECT * FROM table ORDER BY qwerty END

  4. vladimir Says:

    mysql_list_fields() function is deprecated. PHP manual recommends use
    “SHOW COLUMNS FROM tablename” MySQL query instead.
    Example from manual:
    0) {
    while ($row = mysql_fetch_assoc($result)) {
    print_r($row);
    }
    }
    ?>

  5. bawey Says:

    function findColumn($database, $tableName, $columnName){
    $result = $database->query(“select * from “.$tableName.”;”);
    while ($retrievedColumn=$result->fetch_field()){
    if ($retrievedColumn->name==$columnName){
    return true;
    }
    }
    return false;
    }

  6. Achshar Says:

    thnxx :) but yes mysql_list_fields is indeed depreciated..

  7. get ex bf back Says:

    [...] MySQL : Check if field exists | Lost-In-Code [...]

1 Trackbacks For This Post

  1. Tutorial: How to check whether a particular field exist on SQL table - Hungred.com Says:

    [...] the above snippet provided by Antonie Potgieter, the concept is good but it is still not optimum. A better alternative can be written as [...]

Leave a Reply