Add a new column to an existing table in MySql using PHP with PDO

混江龙づ霸主 提交于 2019-12-24 06:13:06

问题


So far I've got this code:

$column_name = strtolower($_POST['<user input>']);
if(!preg_match('/[^A-Za-z0-9.#\\-$]/', $column_name)){
    if(!empty($column_name)){
    $st = $db_pdo->prepare("DESCRIBE <table name>");
    $st->execute();
    $st = $st->fetchAll(PDO::FETCH_COLUMN);
    $compare = $st;

        foreach($compare as $key){
            if($key === $column_name){
                die('Project name already exists. Please select a different name.');
            }
        }

    $st = $db_pdo->prepare("ALTER TABLE emails ADD <column name> varchar");
    $st->execute();  

  } else { echo 'Project name is empty.';}     
} else { echo 'Project name can only contain letters and numbers.';}

A brief overview is:

Check for invalid characters in column name. Check if column name is not empty via a user input. If table already exists, kill the page.

I'm very new to PHP and MySQL and I'm really sorry if these seem like basic questions.

What I want to do is insert a new column into a table with the type varchar length 60. That's it, no other attribute required.

I can't seem to find the appropriate explanation on how to do this with Google so I'm hoping for some pseudo-code with a bit of explanation.

So far I've got this:

$st = $db_pdo->prepare("ALTER TABLE emails ADD <column name> varchar");
$st->execute();

And don't know how to proceed from this.

Thank you.


回答1:


ALTER TABLE emails ADD <column name> varchar(60)

You have to specify length



来源:https://stackoverflow.com/questions/20009987/add-a-new-column-to-an-existing-table-in-mysql-using-php-with-pdo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!