简体   繁体   English

如何动态创建表并在不存在列时更改表

[英]how to create table dynamically and alter table when column not exists

enter
<?php $dob=$_SESSION['dob']; 
 $month=$_SESSION['month'];
 $exists = false;
 $columns = mysql_query("show columns from $month");
 while($c = mysql_fetch_assoc($columns)){
  if($c['Field'] == $dob){
   $exists = true;
   break;
  }
 }     
 if(!$exists){
  mysql_query("ALTER TABLE `$month`  ADD  `$dob` varchar(100) default absent");
 }
 $roll=$_SESSION['var'];
 foreach( $roll as $value=>$roll) {
  $name = mysql_real_escape_string ($roll);
  $sql="insert into $month (roll) values ('$name')";
  mysql_query($sql)or die(mysql_error());
 }
?>

Q:-how to create a table and alter table in mysql php? 问:-如何在m​​ysql php中创建表和更改表?

To create a table do: 要创建表,请执行以下操作:

CREATE TABLE `tableName` (
 ... Columns ...
);

cretae table: 克里特表:

 CREATE TABLE <tablename> (<column_name <data_type>(length if_required), .... );

Alter Table: 修改表:

 ALTER TABLE <tablename> ADD <newcolumnname> <data_type>(length if_required);
 ALTER TABLE <tablename>  DROP <columnname>;
 ALTER TABLE <tablename> MODIFY <columnname> <data_type>(length if_required);

Update table: 更新表:

 UPDATE <tablename> SET <columnname> = <value> WHERE(if_required) <condition>;

Maybe you need this ? 也许您需要这个 This ORM library allow you to develop DB schema on the flight. 这个ORM库允许您在运行中开发数据库模式。 More here . 这里更多。

Or maybe you need so called CODE FIRST STYLE ORM LIBRARY FOR PHP? 或者,也许您需要所谓的CODE代码样式ORM库? I know one but it creates/modifies/alters tables according to your class definitions: 我知道一个,但是它根据您的类定义创建/修改/更改表:

For example if you have: 例如,如果您有:

class user
{
   public $id;
   public $name;
}

Bu default it will create table user with fields id and name. 默认情况下,它将创建具有字段ID和名称的表用户。 Also that framework gives full control on field properties and table properties using doc comments. 该框架还使用doc注释提供了对字段属性和表属性的完全控制。 It is called db.php ( http://db.php ). 它称为db.php( http://db.php )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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