Search code examples
phpsqlmysqldrop-table

How to drop all tables in database without dropping the database itself?


I would like to delete all the tables from database, but not deleting the database itself. Is it possible ? I'm just looking for shorter way than removing the database and create it again. Thanks !


Solution

  • The shortest is to re-create database. but if you don't want to...

    This is for MySQL/PHP. Not tested but something like that.

    $mysqli = new mysqli("host", "my_user", "my_password", "database");
    $mysqli->query('SET foreign_key_checks = 0');
    if ($result = $mysqli->query("SHOW TABLES"))
    {
        while($row = $result->fetch_array(MYSQLI_NUM))
        {
            $mysqli->query('DROP TABLE IF EXISTS '.$row[0]);
        }
    }
    
    $mysqli->query('SET foreign_key_checks = 1');
    $mysqli->close();