开发者

MySQL rename column from within PHP

I need to rename columns in my MySQL table using PHP.

This is made difficult because the syntax is ALTER TABLE [table] CHANGE COLUMN [oldname] [newname] [definition]. The definition is a required parameter.

Is there a way to grab the definition and simply feed this开发者_Python百科 back into the SQL statement? Some sample code would be fantastic, thanks!


According to http://codingforums.com/showthread.php?t=148936, you may have to parse the results of SHOW CREATE TABLE to get the current definition, then use that in the ALTER statement.

mysql_fetch_field() may be useful also.


  1. You can read information_schema.
  2. SHOW TABLE STATUS [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr]


Issue SHOW CREATE TABLE, read off the line describing the column that is of interest, identify the column definition and construct your ALTER TABLE statement.


My solution was this:

$table = "tableName";
$createTableSQL = $dbh->Execute('SHOW CREATE TABLE ' . $table);
$createTableSQL = $createTableSQL[0][1];

$mappingTable = "originalToDevMapping";

//get mapping
$sql = "SELECT origField, newField
        FROM " . $mappingTable;
$newColumns = $dbh->Execute($sql);

foreach ($newColumns as $newColumn) {
    if (strlen($newColumn['newField'])<1) {
        echo "***Removing*** " . $newColumn['origField'] . "<br><br>";

        $sql = "ALTER TABLE " . $table . " DROP COLUMN " . $newColumn['origField'];

        $dbh->Execute($sql);
        if (strlen($dbh->errorStr)>1) {
            echo "<br>************************<br>";
            echo "<br>ERROR:<br>";
            echo $dbh->errorStr;
            echo "<br>************************<br>";
        }

    } else {
        echo "Renaming " .  $newColumn['origField'] . " to " . $newColumn['newField'] . "<br><br>";
        $sql = "ALTER TABLE " . $table . " CHANGE COLUMN " . $newColumn['origField'] . " " . $newColumn['newField'];
        $fieldPos = strpos($createTableSQL,$newColumn['origField']);
        $definitionStart = $fieldPos + strlen($newColumn['origField']) + 2;
        $definitionEnd = strpos($createTableSQL,',',$definitionStart) - 1;
        $definition = substr($createTableSQL,$definitionStart,$definitionEnd-$definitionStart+1);

        //workaround - if enum type, comma is included.  
        if (strstr($definition,'enum')) {
            //look for comma after enum end bracket.
            $commaPos = strpos($createTableSQL, ',', strpos($createTableSQL,')',$definitionStart));
            $definition = substr($createTableSQL,$definitionStart,$commaPos-$definitionStart);
        }

        $dbh->Execute($sql . " " . $definition);
        if (strlen($dbh->errorStr)>1) {
            echo "<br>************************<br>";
            echo "ERROR:<br>";
            echo $dbh->errorStr;
            echo "<br>************************<br>";
        }


    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜