Jump to content

[SOLVED] Automatically add a column to a table if it's missing?


tfburges

Recommended Posts

It's complicated... really complicated.  I have my reasons for wanting to do this.  I'm making a form creator and I'd like to use it as a quick fix for little bugs and glitches that keep unexpectedly popping up.  I know it would be better to just get all my logic aligned beforehand but for right now, adding another few clock cycles to the process isn't going to hurt much as long as it all still works.

 

I know how to use the alter table query.

 

I need to know how to retrieve the "unknown column" and alter the table automatically as soon as the error occurs.

 

I suppose I could do something like...

$query_column = "SELECT `$column_name` FROM `table`";
$result_column = mysql_query($query_column, $link) or die ('MYSQL error: ' . mysql_error());
if (mysql_num_rows($result_column) > 0) {
} else {
mysql_query("ALTER TABLE `table` ADD COLUMN `$column_name` varchar(50)");
}

okay but first off, if your query returns an error because of an unknown column, your die is going to stop the rest of your script, so you aren't going to get a chance to add it.  If you really want to go that route, use a trigger_error instead, so that your script will continue to execute. 

 

But if you can write that script there, why not just check if the column exists and make it if it's not? For instance, you can do this:

 

$sql = "SHOW COLUMNS FROM table";
$result = mysql_query($sql); 

$list = mysql_fetch_assoc($result);
if (in_array($column_name, $list)) {
  // it's there, do something
} else {
   // it's not there, add it
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.