简体   繁体   中英

SQL query to alter table column names

I am running this SQL Query in PHP:

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

to alter column names but before it updates i want to check if the column name already exists and if it does to add a number on the end otherwise to just carry on updating

how can i do this using PHP?

Please, please, please, don't do this. This is about as unsafe a thing to do. However, I will say this: The ALTER TABLE syntax is worth a look:

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

Note that the column_definition bit is not optional.
Also, if you want to see if the fieldname given already exists:

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

Then, in PHP, depending on the extension you used, you do something like this:

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

SHOW COLUMNS will also give you information concerning the type of each field, if it's a key, or even if it's an auto_increment value details, as ever, on the mysql website

So putting it all together:

$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
);

Disclaimer:
The code I posted here is meant to be purely academic. It should not be used, it's unsafe and incomplete. Please rethink what you are trying to do. Avoid, at all cost, using user data to alter how the server stores/structures the data!

Try this

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

In PHP

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

I think you need to specify datatype and default value also. example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM