简体   繁体   中英

Is there a query in mysql which will truncate all the data of tables in a particular database?

$data = mysql_query( "truncate 'DATABASE_NAME' " );

我们可以设法用mysql查询截断数据库的所有表,还是只截断'tablename'这样的单个表?

You could solve that problem by looping over all tables in the database. To get the table names use INFORMATION_SCHEMA of MySQL. A solution could look like this:

//database connection information - adjust as needed
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
//connect to the DB using PDO
$dbh = new PDO($dsn, $user, $password);
//query all tables in a database
$stmt = $dbh->query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='your_database_name_here';");
//truncate tables one by one
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
  $dbh->query('TRUNCATE TABLE '.$row['TABLE_NAME']);
}
unset($stmt, $dbh);

For the sake of brevity any error handling (eg catching exception when the connection to the database cannot be established) is omitted.

Furthermore you should avoid using the old MySQL API, because it has been deprecated in PHP 5.5 and has been removed completely in PHP 7. Instead you should use mysqli or PDO. Take a look at the "Choosing an API" page on php.net to get further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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