Skip to content

Instantly share code, notes, and snippets.

@mbischof
Last active October 1, 2023 18:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbischof/3049758 to your computer and use it in GitHub Desktop.
Save mbischof/3049758 to your computer and use it in GitHub Desktop.
How to drop all tables from database using yii
<?php
$tables = Yii::app()->db->schema->getTableNames();
foreach ($tables as $table) {
Yii::app()->db->createCommand()->dropTable($table);
}
@abudayah
Copy link

how to import tables ?

@pekhota
Copy link

pekhota commented Oct 27, 2014

Hey, don't forget about foreign_key_checks.

<?php 
Yii::app()->db->createCommand("SET foreign_key_checks = 0")->execute();
$tables = Yii::app()->db->schema->getTableNames();  
foreach ($tables as $table) {  
    Yii::app()->db->createCommand()->dropTable($table);  
}  
Yii::app()->db->createCommand("SET foreign_key_checks = 1")->execute();

Works a little better.

@CyberPunkCodes
Copy link

Neither one of your code should work. You need to add ->execute() after dropTable().

Also, app() doesn't exist... It should be $app.

Fixed code below, or view my Fork of this Gist:

<?php
Yii::$app->db->createCommand("SET foreign_key_checks = 0")->execute();
$tables = Yii::$app->db->schema->getTableNames();

foreach ($tables as $table) {
    Yii::$app->db->createCommand()->dropTable($table)->execute();
}

Yii::$app->db->createCommand("SET foreign_key_checks = 1")->execute();

Hope it helps 👍

@mbischof
Copy link
Author

oh comments

@pekhota, you're right, that works better
@wade, my code is from old yii 1.1. days

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment