How to create multiple tables at once?

Asked

Viewed 202 times

1

I wonder how I can make this code below run the creation of several tables with mysqli_ at the same time because at the moment this code being executed only creates a single precise table that it creates in the case all the tables below in bold or even more if you want and also allow to create values INSERT INTO also multiple.

Tables: medias_category, banners, medias, covers, serials, configurations

Obs: If necessary by these tables for my question to be better interpreted please leave in the comments that I will update the question.

And I put only the first table since it is not running the creation of more than one at a time.

// Conectar ao banco de dadso MYSQLI
$connect = new mysqli($_POST['db_host'], $_POST['db_user'], $_POST['db_pw'], $_POST['db_name']);
// Checar Conexão
if ($connect->connect_error) {
    die("Erro na Conexão: " . $connect->connect_error);
} 

// sql criar tabelas
$sql = "CREATE TABLE `medias_categoria` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `medias_categoria_url` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `nome` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `modo` enum('UNICO','MULTIPLO') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'UNICO',
  `data` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `categoriaUnica` (`animes_categoria_url`),
  UNIQUE KEY `nomeUnico` (`nome`),
  KEY `colunasIndexadas` (`id`,`animes_categoria_url`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;";

if ($connect->query($sql) === TRUE) {
    echo "Table MyGuests created successfully";

} else {
    echo "Error creating table: " . $conn->error;
}

1 answer

3


You can just use the function mysqli_multi_query which allows you to execute several query at the same time.

Example:

$sql = "CREATE TABLE `medias_categoria` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `medias_categoria_url` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `nome` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `modo` enum('UNICO','MULTIPLO') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'UNICO',
  `data` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `categoriaUnica` (`animes_categoria_url`),
  UNIQUE KEY `nomeUnico` (`nome`),
  KEY `colunasIndexadas` (`id`,`animes_categoria_url`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; "

$sql .= "CREATE TABLE `banners` ... ; ";
// depois as restantes

$connect->multi_query( $sql );

// ou mysqli_multi_query ( $connect , $sql );

Although I recommend you create one table at a time.

$connect->query( $sql_medias_categoria );
$connect->query( $sql_banners          );
// depois as restantes

Note: Do not forget the dependency between tables or you can screw up.

  • 1

    Grateful for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.