用于更改表列名的SQL查询

时间:2014-05-21 12:34:28

标签: php mysql

我在PHP中运行此SQL查询:

$sql="alter table callplandata change '".$_POST["col_name$y"]."' '".$_POST["col_newname$y"]."' ";

更改列名但在更新之前我想检查列名是否已存在以及是否在末尾添加数字,否则只进行更新

我怎么能用PHP做到这一点?

3 个答案:

答案 0 :(得分:2)

请拜托,请不要这样做。这是一件不安全的事情。但是,我会这样说:ALTER TABLE syntax值得一看:

ALTER TABLE <table name>
    CHANGE [COLUMN] old_col_name new_col_name column_definition

请注意, column_definition 不是可选。
此外,如果您想查看给定的字段名是否已存在:

SHOW COLUMNS FROM <table_name> /* or SHOW COLUMNS IN tbl */

然后,在PHP中,根据您使用的扩展名,您可以执行以下操作:

$existingFields = array();
foreach ($resultSet as $row)
{
    $existingFields[] = $row['Field'];
}

SHOW COLUMNS还会为您提供有关每个字段类型的信息,如果它是密钥,或者即使它是auto_increment值details, as ever, on the mysql website

所以把它们放在一起:

$db = new PDO();//connect
$stmt = $db->prepare('SHOW COLUMNS IN callplandata WHERE Field = :field');
$bind = array(
    ':field'    => $_POST['colname_new']
);
$stmt->execute($bind);
if ($row = $stmt->fetch())
    throw new InvalidArgumentException($_POST['colname_new'].' already exists!');
$bind[':field'] = $_POST['colname_old'];
$stmt->closeCursor();//reset cursor, so we can re-use the statement
$stmt->execute($bind);//re-use statement
if (!($row = $stmt->fetch(PDO::FETCH_OBJ))
    throw new InvalidArgumentException($_POST['colname_old'].' does not exist, cannot rename it!');
//very basic column definition construction here, needs more work, though!
$current = '';
$current = $row->Type. ' '.($row->Null == 'NO' ? 'NOT NULL ' : '').
    ($row->Default !== '' ? 'DEFAULT '.$row->Default.' ' : '').$row->Extra;
/**
 * ADD CODE HERE TO SANITIZE THE NEW COLUMN NAME
 * if you want to procede with this madness... I would urge you not to, though!
 */
$pdo->exec(
    'ALTER TABLE callplandata
         CHANGE '.$_POST['colname_old'].' '.$_POST['colname_new'].' './/rename
    $current//add column definition
);

声明:
我在这里发布的代码纯粹是学术性的。它不应该被使用,它是不安全和不完整的。请重新考虑您要做的事情。不惜一切代价避免使用用户数据来改变 服务器 存储/构建数据的方式!

答案 1 :(得分:1)

试试这个

SELECT * 
FROM information_schema.COLUMNS 
WHERE 
TABLE_SCHEMA = 'db_name' 
AND TABLE_NAME = 'table_name' 
AND COLUMN_NAME = 'column_name'

在PHP中

$result = mysqli_query("SHOW COLUMNS FROM `table` LIKE 'fieldname'");
$exists = (mysqli_num_rows($result))?TRUE:FALSE;

答案 2 :(得分:0)

我认为您还需要指定数据类型和默认值。 例子

ALTER TABLE `ca_4_4_14`  CHANGE `active` `is_active` ENUM('Y','N') CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT 'Y' NOT NULL;