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′;");
}
$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.







November 10th, 2008 at 4:39 am
$tableFields = mysql_list_fields(”databasename”, “tablename”);
has to be changed to
$fields = mysql_list_fields(”databasename”, “tablename”);