MySQL Add Column if Not Exists - PHP Function
Mar 13, 2008 · 1 minute readCategory: mysqlphp
This is post is now quite old and the the information it contains may be out of date or innacurate.
If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub
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;
$columns = mysql_query("show columns from $db");
while($c = mysql_fetch_assoc($columns)){
if($c['Field'] == $column){
$exists = true;
break;
}
}
if(!$exists){
mysql_query("ALTER TABLE `$db` ADD `$column` $column_attr");
}
}
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.