在MySQL中动态检查和创建表

时间:2016-10-27 13:19:36

标签: php mysql mysqli

我在数据库中创建动态表时遇到问题。如果该表已存在于数据库中,则不应创建新表。

if( mysqli_num_rows(mysqli_query("SHOW TABLES LIKE abc")) == 1){
    echo "Already Exit";    
} else {
    //echo "not exit";
    $sql="CREATE TABLE `decoration`.`newtable` (`id` INT NOT NULL AUTO_INCREMENT ,`company_id` VARCHAR( 20 ) NOT NULL ,`list_name` VARCHAR( 50 ) NOT NULL ,`created` INT NOT NULL ,`modified` INT NOT NULL ,`status` INT NOT NULL ,PRIMARY KEY (  `id` )) ENGINE = INNODB";
    if ($con->mysqli_query($sql)){
        echo "created";
    } else {
        echo "not created";
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用以下查询

CREATE TABLE IF NOT EXISTS `schema`.`Employee` (
`idEmployee` VARCHAR(45) NOT NULL ,
`Name` VARCHAR(255) NULL ,
`idAddresses` VARCHAR(45) NULL ,
PRIMARY KEY (`idEmployee`) ,
CONSTRAINT `fkEmployee_Addresses`
FOREIGN KEY `fkEmployee_Addresses` (`idAddresses`)
REFERENCES `schema`.`Addresses` (`idAddresses`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin

IF NOT EXISTS将检查表是否存在,如果数据库中存在表,则不会创建新表。

参考:http://dev.mysql.com/doc/refman/5.7/en/create-table.html

希望这会有所帮助!