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

Link to comment
Share on other sites

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
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.