使用PHP和PDO将新列添加到MySql中的现有表中 [英] Add a new column to an existing table in MySql using PHP with PDO

查看:80
本文介绍了使用PHP和PDO将新列添加到MySql中的现有表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经有了以下代码:

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.';}

简要概述是:

检查列名中的无效字符. 通过用户输入检查列名是否不为空. 如果表已经存在,请杀死该页面.

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.

我对PHP和MySQL还是很陌生,如果这些问题看起来像是基本问题,我感到非常抱歉.

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

我想要做的是将一个新列插入类型为varchar长度为60的表中.就是这样,不需要其他属性.

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.

我似乎找不到有关如何在Google上执行此操作的适当说明,因此我希望能提供一些伪代码并提供一些说明.

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.

谢谢.

推荐答案

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

您必须指定长度

这篇关于使用PHP和PDO将新列添加到MySql中的现有表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆