MySQL Add Column if Not Exists - PHP Function
March 13th, 2008Read More mysql, php
This is a nice little function which I struggled to find elsewhere on the web.
As discussed elsewhere this is not the kind of thing that should be included in a public facing script, but for administration tools etc its pretty handy:
-
function add_column_if_not_exist($db, $column, $column_attr = "VARCHAR( 255 ) NULL" ){
-
$exists = false;
-
if($c['Field'] == $column){
-
$exists = true
-
break;
-
}
-
}
-
if(!$exists){
-
}
-
}
This function grabs the column information for the table, then it loops through the info looking for the column. If it finds the column then it acknowledges that it exists and ceases the loop.
After this stage, the function checks to see if exists is true or not, and if it is not true then it adds the column with the attributes defined when calling the function.
The default attributes are for a VARCHAR field up to 255 characters in length and NULL enabled.

May 30th, 2008 at 2:14 pm
You could also do:
if (false === mysql_query("select colname from tablename limit 0")) {
//add the column
}
May 30th, 2008 at 2:28 pm
would this not give a false negative if the table was empty?
December 30th, 2008 at 1:45 pm
Thanks.