我需要使用PHP重命名MySQL表中的列。
这很难,因为语法是ALTER TABLE [table] CHANGE COLUMN [oldname] [newname] [definition]
。该定义是必需参数。
有没有办法获取定义并简单地将其反馈到SQL语句中?一些示例代码非常棒,谢谢!
答案 0 :(得分:1)
根据http://codingforums.com/showthread.php?t=148936,您可能需要解析SHOW CREATE TABLE
的结果以获取当前定义,然后在ALTER
语句中使用该结果。
mysql_fetch_field()也可能有用。
答案 1 :(得分:0)
information_schema
。
<击> 撞击> SHOW TABLE STATUS [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr]
击> 答案 2 :(得分:0)
问题SHOW CREATE TABLE
,读取描述感兴趣的列的行,确定列定义并构建您的ALTER TABLE
语句。
答案 3 :(得分:0)
我的解决方案是:
$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>";
}
}
}