25 April 2014

How To Add Column In Table If Not Exist ?

Hello everyone,

Today i am sharing little information about MySql alteration with database table.

I have added following function to help you to create column in db table if column not exist.

/**
 * To Add Column In Table If Not Exist.
 * @param $db_name Database Name
 * @param $table Table Name
 * @param $column Column Name
 * @param $column_attr Column attributs
 */
function add_column_if_not_exist($db_name, $table, $column_name, $column_attr = "VARCHAR( 255 ) NULL" )
{
 $exists = false;
 $columns = mysql_query("SELECT * FROM information_schema.COLUMNS WHERE `TABLE_SCHEMA`='$db_name' AND `TABLE_NAME`='$table' AND `COLUMN_NAME`='$column_name'");
 if(mysql_num_rows($columns) == 0)
 {
  mysql_query("ALTER TABLE `$table` ADD `$column_name`  $column_attr");
 }
}

I hope that, this will be helpful to you.

Have Fun!

No comments:

Post a Comment